How to Add and Subtract Months from a Date in Pandas


You can use the following methods to add and subtract months from a date in pandas:

Method 1: Add Months to Date

from pandas.tseries.offsets import DateOffset

df['date_column'] + DateOffset(months=3)

Method 2: Subtract Months from Date

from pandas.tseries.offsets import DateOffset

df['date_column'] - DateOffset(months=3)

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': pd.date_range(start='1/5/2022', freq='M', periods=10),
                   'sales': [6, 8, 9, 5, 4, 8, 8, 3, 5, 9]})

#view DataFrame
print(df)

        date  sales
0 2022-01-31      6
1 2022-02-28      8
2 2022-03-31      9
3 2022-04-30      5
4 2022-05-31      4
5 2022-06-30      8
6 2022-07-31      8
7 2022-08-31      3
8 2022-09-30      5
9 2022-10-31      9

Example 1: Add Months to Date in Pandas

The following code shows how to create a new column that adds 3 months to the value in the date column:

from pandas.tseries.offsets import DateOffset

#create new column that adds 3 months to date
df['date_plus3'] = df.date + DateOffset(months=3)

#view updated DataFrame
print(df)

        date  sales date_plus3
0 2022-01-31      6 2022-04-30
1 2022-02-28      8 2022-05-28
2 2022-03-31      9 2022-06-30
3 2022-04-30      5 2022-07-30
4 2022-05-31      4 2022-08-31
5 2022-06-30      8 2022-09-30
6 2022-07-31      8 2022-10-31
7 2022-08-31      3 2022-11-30
8 2022-09-30      5 2022-12-30
9 2022-10-31      9 2023-01-31

The new column date_plus3 represents the values in the date column with three months added to each value.

Example 2: Subtract Months from Date in Pandas

The following code shows how to create a new column that subtracts 3 months to the value in the date column:

from pandas.tseries.offsets import DateOffset

#create new column that subtracts 3 months from date
df['date_minus3'] = df.date + DateOffset(months=3)

#view updated DataFrame
print(df)

        date  sales date_minus3
0 2022-01-31      6  2021-10-31
1 2022-02-28      8  2021-11-28
2 2022-03-31      9  2021-12-31
3 2022-04-30      5  2022-01-30
4 2022-05-31      4  2022-02-28
5 2022-06-30      8  2022-03-30
6 2022-07-31      8  2022-04-30
7 2022-08-31      3  2022-05-31
8 2022-09-30      5  2022-06-30
9 2022-10-31      9  2022-07-31

The new column date_minus3 represents the values in the date column with three months 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

Leave a Reply

Your email address will not be published. Required fields are marked *