Last Updated on March 3, 2022 by Jay
This tutorial will show you how to add and subtract days to/from a date variable in Python and pandas.
We often use the datetime class to represent date and time related data. Datetime offers many convenient functions; however, we can’t intuitively add or subtract numbers from a datetime object. We need to use the timedelta object instead.
Let’s take a look at the following example:
import datetime as dt
tdy = dt.datetime.today()
print(tdy)
2022-03-02 23:41:44.287343
If we try to add 10 to the tdy variable, we’ll get the following error message:
tdy + 10 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_29580/2199066677.py in <module> ----> 1 tdy + 10 TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'int'
Add Days to A Date
We need to use the datetime.timedelta object to model number of days.
tdy + dt.timedelta(days = 10)
datetime.datetime(2022, 3, 12, 23, 41, 44, 287343)
The maximum unit for a timedelta object is weeks, but it’s easier to use days in many cases. To model months or years, we can do something like this:
month = dt.timedelta(days = 30)
year = dt.timedelta(days = 365)
month * 3
datetime.timedelta(days=90)
year * 10
datetime.timedelta(days=3650)
tdy + month * 3
datetime.datetime(2022, 5, 31, 23, 41, 44, 287343)
tdy + year * 10
datetime.datetime(2032, 2, 28, 23, 41, 44, 287343)
Subtract Days from A Date
We can also subtract a certain number of days from a date easily using timedelta object:
tdy - year * 10
datetime.datetime(2012, 3, 4, 23, 41, 44, 287343)
Unfortunately, datetime has its limitations and can’t model exact months or years easily. Another 3rd party module dateutil can do that, which will be for another topic.
Add Days to A Date Column in Python Pandas
Let’s look at the following simple pandas dataframe containing just 1 date column. We specify the data type is M8[ns], or datetime64[ns].
import pandas as pd
df = pd.DataFrame(
{'date':['2021-12-01', '2022-01-01','2022-02-01','2022-03-01','2022-04-01','2022-05-01']},
dtype='<M8[ns]')
date
0 2021-12-01
1 2022-01-01
2 2022-02-01
3 2022-03-01
4 2022-04-01
5 2022-05-01
We can use the timedelta object again to add or subtract days from a pandas dataframe column:
df['date'] + dt.timedelta(days = 10)
0 2021-12-11
1 2022-01-11
2 2022-02-11
3 2022-03-11
4 2022-04-11
5 2022-05-11
Name: date, dtype: datetime64[ns]
Additional Resources
How to Convert Column to Datetime in Pandas