Difference between revisions of "Python dates"
Jump to navigation
Jump to search
| (3 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
Python dates are a notorious pain in the ass. Here's a short field guide. | Python dates are a notorious pain in the ass. Here's a short field guide. | ||
| + | |||
| + | ===Resources=== | ||
| + | * A strptime guide from [https://www.digitalocean.com/community/tutorials/python-string-to-datetime-strptime Digital Ocean] | ||
| + | * A tutorial on the <code>calendar</code> module from [https://pynative.com/python-get-the-day-of-week/#h-get-the-weekday-name-from-date-using-calendar-module PyNative] | ||
| + | * | ||
| + | |||
===Object types=== | ===Object types=== | ||
When using <code> pd.to_datetime </code> with a text date (e.g., '2022-05-19'), the result is a ''timestamp'' object. | When using <code> pd.to_datetime </code> with a text date (e.g., '2022-05-19'), the result is a ''timestamp'' object. | ||
| Line 26: | Line 32: | ||
<syntaxhighlight lang=Python> | <syntaxhighlight lang=Python> | ||
df['times'] = pd.to_datetime(df['times']) # convert column to pandas Timestamp | df['times'] = pd.to_datetime(df['times']) # convert column to pandas Timestamp | ||
| − | df['times'] = [x.time() for x in df['times'] # list comprehension to convert entire column | + | df['times'] = [x.time() for x in df['times']] # list comprehension to convert entire column |
| − | df['times'].iloc[0] # time | + | df['times'].iloc[0] # time was originally "06:30 PM" |
datetime.time(18, 30) | datetime.time(18, 30) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| + | |||
| + | ===Basic operations=== | ||
| + | Today's date as a date: | ||
| + | dt.datetime.date() | ||
| + | datetime.date(2023,11,18) | ||
| + | |||
| + | Today's date in ISO 8601 format: | ||
| + | dt.datetime.now().isoformat() | ||
| + | |||
| + | Add days to a date: | ||
| + | dt.date.today() + dt.timedelta(days=7) | ||
| + | |||
| + | Days between dates: | ||
| + | (dt.date(2025,12,31) - dt.date(2025,6,4)).days | ||
| + | |||
| + | Get weekday name of a date: | ||
| + | dt.datetime(2025,9,5).strftime("%A") | ||
| + | |||
| + | Get a range of dates with NumPy: | ||
| + | np.arange('2025-06-01', '2025-06-14', dtype='datetime64[D]') | ||
| + | # Range of months | ||
| + | np.arange('2025-06-01', '2025-12-01', dtype='datetime64[M]') | ||
| + | |||
| + | Get a UNIX-epoch timestamp: | ||
| + | dt.datetime(2025,6,4,0,0,0).timestamp() | ||
Latest revision as of 21:49, 4 June 2025
Python dates are a notorious pain in the ass. Here's a short field guide.
Resources[edit]
- A strptime guide from Digital Ocean
- A tutorial on the
calendarmodule from PyNative
Object types[edit]
When using pd.to_datetime with a text date (e.g., '2022-05-19'), the result is a timestamp object.
df['Date'].iloc[0] # this value has been converted from string date w/ pd.to_datetime
Timestamp('2022-05-19 00:00:00')
If you take a date string and use the datetime.datetime.strptime function, the result is a datetime.datetime object:
import datetime as dt
dstr = '2022-05-19'
dobj = dt.datetime.strptime(dstr, '%Y-%m-%d')
dobj
datetime.datetime(2022, 5, 19, 0, 0)
In addition, there's also a datetime.date object, which truncates the time and just gives you a date:
dateobj = dt.datetime.strptime(dstr, '%Y-%m-%d').date()
dateobj
datetime.date(2022, 5, 19)
Here is a cheatsheet for the codes used in str[pf]time (e.g., '%Y' means YYYY, etc.)
To extract a time from a pandas Timestamp object:
df['times'] = pd.to_datetime(df['times']) # convert column to pandas Timestamp
df['times'] = [x.time() for x in df['times']] # list comprehension to convert entire column
df['times'].iloc[0] # time was originally "06:30 PM"
datetime.time(18, 30)
Basic operations[edit]
Today's date as a date:
dt.datetime.date() datetime.date(2023,11,18)
Today's date in ISO 8601 format:
dt.datetime.now().isoformat()
Add days to a date:
dt.date.today() + dt.timedelta(days=7)
Days between dates:
(dt.date(2025,12,31) - dt.date(2025,6,4)).days
Get weekday name of a date:
dt.datetime(2025,9,5).strftime("%A")
Get a range of dates with NumPy:
np.arange('2025-06-01', '2025-06-14', dtype='datetime64[D]')
# Range of months
np.arange('2025-06-01', '2025-12-01', dtype='datetime64[M]')
Get a UNIX-epoch timestamp:
dt.datetime(2025,6,4,0,0,0).timestamp()