To add months to a datetime variable using Python, the easiest way is to use the Python relativedelta() function from the dateutil module.
from datetime import datetime
from dateutil.relativedelta import relativedelta
now = datetime.now()
two_months_in_future = now + relativedelta(months=2)
print(now)
print(two_months_in_future)
#Output:
2022-02-09 08:58:25.940729
2022-04-09 08:58:25.940729
When working with data in Python, many times we are working with dates. Being able to manipulate and change dates easily is very important for efficient processing.
One such change is to be able to add months to a datetime variable.
With Python, we can easily add months to a datetime variable with the help of the datetime module and dateutil module.
To add months to a datetime in Python, we can use the relativedelta() function from the dateutil module.
Below is code that shows you how to add months to get some dates in the future using Python.
from datetime import datetime
from dateutil.relativedelta import relativedelta
now = datetime.now()
two_months_in_future = now + relativedelta(months=2)
six_months_in_future = now + relativedelta(months=6)
one_year_in_future = now + relativedelta(months=12)
print(now)
print(two_months_in_future)
print(six_months_in_future)
print(one_year_in_future)
#Output:
2022-02-09 08:58:25.940729
2022-04-09 08:58:25.940729
2022-08-09 08:58:25.940729
2023-02-09 08:58:25.940729
If instead you’d like to subtract months from a date in Python, you can use a very similar method as shown above but subtract the timedelta function.
You can also use dates with the code above. The difference between dates and datetimes are that dates don’t have a time associated with them.
from datetime import date
from dateutil.relativedelta import relativedelta
now = date,today()
two_months_in_future = now + relativedelta(months=2)
six_months_in_future = now + relativedelta(months=6)
one_year_in_future = now + relativedelta(months=12)
print(now)
print(two_months_in_future)
print(six_months_in_future)
print(one_year_in_future)
#Output:
2022-02-09
2022-04-09
2022-08-09
2023-02-09
How to Add Months to a Date With pandas in Python
If you are using the Python pandas module, we can add months to a date variable easily.
With pandas, to add months to a date, we use the DateOffset() function.
Below is an example of how to use pandas to add months to a date in Python.
import pandas as pd
startdate = "01/29/2022"
enddate = pd.to_datetime(startdate) + pd.DateOffset(months=5)
print(startdate)
print(enddate)
#Output:
2022-01-29 00:00:00
2022-06-29 00:00:00
Hopefully this article has been beneficial for you to learn how to add months to a date and datetime using Python.