Working with Dates in Pandas

Canonical import statements

import pandas as pd

Timestamp objects contain both date and time information. They are analogous to datetime objects.

pd.Timestamp('9/1/2016 10:05AM')
Timestamp('2016-09-01 10:05:00')

Period objects are time durations. They are analogous to timedelta objects.

pd.Period('1/2016')
Period('2016-01', 'M')
pd.Period('3/5/2016')
Period('2016-03-05', 'D')

Various string formats of dates can be converted to Timestamp objects.

ds = pd.DataFrame(['2 June 2013', 'Aug 29, 2014', '2015-06-26', '7/12/16'])
ds[1] = pd.to_datetime(ds[0])
ds

0 1
0 2 June 2013 2013-06-02
1 Aug 29, 2014 2014-08-29
2 2015-06-26 2015-06-26
3 7/12/16 2016-07-12

Pandas has built-in ways of generating datetimes at specified intervals.

dates = pd.date_range('10-01-2016', periods=9, freq='2W-SUN')
dates = pd.DataFrame(dates)
dates

0
0 2016-10-02
1 2016-10-16
2 2016-10-30
3 2016-11-13
4 2016-11-27
5 2016-12-11
6 2016-12-25
7 2017-01-08
8 2017-01-22

The accessor methods Pandas provides work as you would expect.

dates['Year'] = dates[0].dt.year
dates['Month'] = dates[0].dt.month
dates['Day'] = dates[0].dt.day
dates['Weekday'] = dates[0].dt.weekday
dates

0 Year Month Day Weekday
0 2016-10-02 2016 10 2 6
1 2016-10-16 2016 10 16 6
2 2016-10-30 2016 10 30 6
3 2016-11-13 2016 11 13 6
4 2016-11-27 2016 11 27 6
5 2016-12-11 2016 12 11 6
6 2016-12-25 2016 12 25 6
7 2017-01-08 2017 1 8 6
8 2017-01-22 2017 1 22 6