Difference between revisions of "Python dates"
Jump to navigation
Jump to search
| 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. | ||
===Object types=== | ===Object types=== | ||
| − | When using <code> pd.to_datetime </code> with a text date (e.g., '2022-05-19'), the result is a | + | When using <code> pd.to_datetime </code> with a text date (e.g., '2022-05-19'), the result is a ''timestamp'' object. |
<syntaxhighlight lang=Python> | <syntaxhighlight lang=Python> | ||
df['Date'].iloc[0] # this value has been converted from string date w/ pd.to_datetime | df['Date'].iloc[0] # this value has been converted from string date w/ pd.to_datetime | ||
Timestamp('2022-05-19 00:00:00') | Timestamp('2022-05-19 00:00:00') | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| − | If you take a date string and use the <code>datetime.datetime.strptime</code> function, the result is a | + | If you take a date string and use the <code>datetime.datetime.strptime</code> function, the result is a ''datetime.datetime'' object: |
<syntaxhighlight lang=Python> | <syntaxhighlight lang=Python> | ||
import datetime as dt | import datetime as dt | ||
Revision as of 20:03, 18 November 2023
Python dates are a notorious pain in the ass. Here's a short field guide.
Object types
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)