Difference between revisions of "Python dates"

From Bitnami MediaWiki
Jump to navigation Jump to search
Line 22: Line 22:
 
</syntaxhighlight>
 
</syntaxhighlight>
 
Here is a [https://strftime.org/ cheatsheet] for the codes used in <code>str[pf]time</code> (e.g., '%Y' means YYYY, etc.)
 
Here is a [https://strftime.org/ cheatsheet] for the codes used in <code>str[pf]time</code> (e.g., '%Y' means YYYY, etc.)
 +
 +
To extract a time from a pandas <code>Timestamp</code> object:
 +
<syntaxhighlight lang=Python>
 +
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 is 6:30 PM
 +
datetime.time(18, 30)
 +
</syntaxhighlight>

Revision as of 20:40, 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)

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 is 6:30 PM
datetime.time(18, 30)