Add months to a date in Python

This article will give you a few methods to “Add months to a date” in Python by using the datetime module and pandas library. Do not miss us if you are confused about how to do that. We will provide detailed examples with implementation and explanation. 

Working with time in Python

In Python, you feel easy to work with the time, such as hour, day, month, year, etc., by using the datetime module. The module provides strong APIs to manipulate time effectively. To use the module without errors, import it in the beginning by the syntax:

import datetime

Also, the pandas library provides helpful functions to work with the time. This tutorial will show you how to use the DateOffset class to add months to a date.

Methods to Add months to a date in Python

Use the timedelta class from the datatime module

The timedelta class allows you to specify the amount of time to add or subtract using days, seconds, microseconds, etc. In this case, we are using days=90 to add three months, but this may only be accurate for some months as they have more or fewer days than others. If you need to add a specific number of months, you may need to use a different approach.

Code:

from datetime import timedelta, date
 
# Create a date object for the current date
current = date(2022, 12, 27)
 
# Add 3 months to the current date
threeMonthsLater = current + timedelta(days=90)
 
print("Current time is:", current)
print("3 months later is:", threeMonthsLater)

Result:

Current time is: 2022-12-27
3 months later is: 2023-03-27

Use the relativedelta class from the dateutil module

Similarly, you can use the relativedelta class from the dateutil module to get the same result.

Code:

from dateutil.relativedelta import relativedelta
from datetime import date
 
# Create a date object for the current date
current = date(2022, 12, 27)
 
# Add 3 months to the current date
threeMonthsLater = current + relativedelta(months=3)
 
print("Current time is:", current)
print("3 months later is:", threeMonthsLater)

Result:

Current time is: 2022-12-27
3 months later is: 2023-03-27

Use the DateOffset class from the pandas library

Here is an example of using the DateOffet class from the pandas library to add three months to a date.

Code:

import pandas as pd
 
# Create a date object for the current date
current = pd.Timestamp("2022-12-27")
 
# Add 3 months to the current date
threeMonthsLater = current + pd.DateOffset(months=3)
 
print("Current time is:", current)
print("3 months later is:", threeMonthsLater)

Result:

Current time is: 2022-12-27 00:00:00
3 months later is: 2023-03-27 00:00:00

Summary

In summary, to add months to a date in Python, you can use the timedelta class from the datetime module or the relativedelta class from the dateutil module. Moreover, you can use the DateOffset class from the pandas library to work more effectively with a dataframe.

Leave a Reply

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