Working with datetimes

cheatsheet
pandas
Author

Teresa Kubacka

Published

July 26, 2022

Working with datetimes

import pandas as pd

To extract just date from a full datetime

s = pd.Series(pd.date_range("20130101", periods=4, freq='H'))
s
0   2013-01-01 00:00:00
1   2013-01-01 01:00:00
2   2013-01-01 02:00:00
3   2013-01-01 03:00:00
dtype: datetime64[ns]

Keep just the date:

s.dt.date
0    2013-01-01
1    2013-01-01
2    2013-01-01
3    2013-01-01
dtype: object

Keep just the date as datetime object:

s.dt.date.astype('datetime64')
0   2013-01-01
1   2013-01-01
2   2013-01-01
3   2013-01-01
dtype: datetime64[ns]

Keep just the date by resetting the timestamp:

s.dt.normalize()
0   2013-01-01
1   2013-01-01
2   2013-01-01
3   2013-01-01
dtype: datetime64[ns]

Keep the date with a particular formatting:

s.dt.strftime("%Y/%m/%d")
0    2013/01/01
1    2013/01/01
2    2013/01/01
3    2013/01/01
dtype: object

Links:
- source
- .dt docs