You can use the following methods to add and subtract days from a date in pandas:
Method 1: Add Days to Date
df['date_column'] + pd.Timedelta(days=5)
Method 2: Subtract Days from Date
df['date_column'] - pd.Timedelta(days=5)
The following examples show how to use each method in practice with the following pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'date': ['2022-10-01', '2022-10-23', '2022-10-30', '2022-11-05'],
'sales': [450, 567, 612, 701]})
#convert date column to datetime
df['date'] = pd.to_datetime(df['date'])
#view DataFrame
print(df)
date sales
0 2022-10-01 450
1 2022-10-23 567
2 2022-10-30 612
3 2022-11-05 701
Example 1: Add Days to Date in Pandas
The following code shows how to create a new column that adds five days to the value in the date column:
#create new column that adds 5 days to value in date column
df['date_plus_five'] = df['date'] + pd.Timedelta(days=5)
#view updated DataFrame
print(df)
date sales date_plus_five
0 2022-10-01 450 2022-10-06
1 2022-10-23 567 2022-10-28
2 2022-10-30 612 2022-11-04
3 2022-11-05 701 2022-11-10
The new column date_plus_five represents the values in the date column with five days added to each value.
We can also use the dtypes function to confirm that the new column is indeed a datetime column:
#check data type of each column
df.dtypes
date datetime64[ns]
sales int64
date_plus_five datetime64[ns]
dtype: object
Both the date and date_plus_five columns are recognized as datetime formats.
Example 2: Subtract Days from Date in Pandas
The following code shows how to create a new column that subtracts five days from the value in the date column:
#create new column that subtracts five days from date
df['date_minus_five'] = df['date'] - pd.Timedelta(days=5)
#view updated DataFrame
print(df)
date sales date_minus_five
0 2022-10-01 450 2022-09-26
1 2022-10-23 567 2022-10-18
2 2022-10-30 612 2022-10-25
3 2022-11-05 701 2022-10-31
The new column date_minus_five represents the values in the date column with five days subtracted from each value.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Convert Columns to DateTime in Pandas
How to Convert Datetime to Date in Pandas
How to Extract Month from Date in Pandas