- Add months to a date in Python
- Add months to a date in Python using relativedelta
- Frequently Asked:
- Add months to a date in Python using Pandas
- Related posts:
- Python time add month
- # Add months to a date in Python
- # Installing python-dateutil
- # Add months to the current date
- # Extracting the date after adding months
- # Using a formatted-string literal to format the date
- # Creating a datetime object from a date string and adding months
- # Adding months to the current date using a datetime object
- # Additional Resources
- Add Month to datetime in Python
- Ways to add month to datetime in Python
- Using the datetime.datetime constructor to add month to datetime in Python.
- Using the dateutil.relativedelta object to add month to datetime in Python
Add months to a date in Python
In this artilce we will discuss different ways to add months to a given date in python.
Suppose we have a date ’21/1/2021′ and we want to add N months to it and N can be 1, 20, 50 or any other number. We want the final date after adding N months in the given date. Let’s see how to do that,
Add months to a date in Python using relativedelta
In python, the dateutil module provides a class relativedelta, which represents an interval of time. The relativedelta class has following attributes which tells about the duration,
To add N months in a given date, create a relativedelta object representing the interval of N months and then add that to the datetime object to get the final date.
Detailed steps to add N months to date are as follows,
Frequently Asked:
- Step 1: If the given date is in a string format, then we need to convert it to the datetime object. For that we can use the datetime.strptime() function. Whereas, if the given date is already a datetime object, then you can skip this step.
- Step 2: Create an object of relativedelta, to represent an interval of N months. For that, pass the argument months with value N in the relativedelta constructor.
- Step 3: Add the relativedelta object to the datetime object. It will give us a datetime object point to a date i.e. N months after the given date.
- Step 4: If you want the final date in string format, then convert the datetime object to string using strftime(). You can pass the format string as argument and it will convert the datetime object to a string of the specified format.
Let’s understand with an example,
Add 20 months to a date in python
from datetime import datetime from dateutil.relativedelta import relativedelta given_date = '21/1/2021' print('Give Date: ', given_date) date_format = '%d/%m/%Y' dtObj = datetime.strptime(given_date, date_format) # Add 20 months to a given datetime object n = 20 future_date = dtObj + relativedelta(months=n) print('Date after 20 months: ', future_date) print('Date after 20 months: ', future_date.date()) # Convert datetime object to string in required format future_date_str = future_date.strftime(date_format) print('Date after 20 months (as string): ', future_date_str)
Give Date: 21/1/2021 Date after 20 months: 2022-09-21 00:00:00 Date after 20 months: 2022-09-21 Date after 20 months (as string): 21/09/2022
We added 20 months in the date ’21/1/2021′ to make it ’21/09/2022′.
As we added relativedelta (of 20 months duration) to the datetime object, so it returned a new datetime object pointing to the final date. As datetime object has the the timestamp also, therefore it also got printed. If you want date only, then you can fetch the date object from datetime object using date() function, just like we did in above example. In the end we converted the datetime object to the required string format using datetime.strftime().
Add months to a date in Python using Pandas
Pandas provide a class DateOffset, to store the duration or interval information. It is mostly used to increment or decrement a timestamp. It can be used with datetime module to to add N months to a date.
Let’s understand with an example,
Add 10 months to a date in python
from datetime import datetime import pandas as pd given_date = '1/21/2021' print('Give Date: ', given_date) # Convert date string to datetime object date_format = '%m/%d/%Y' dtObj = datetime.strptime(given_date, date_format) # Add 10 months to a given datetime object n = 10 future_date = dtObj + pd.DateOffset(months=n) print('Date after 10 months: ', future_date) print('Date after 10 months: ', future_date.date()) # Convert datetime object to string in required format future_date_str = future_date.strftime(date_format) print('Date after 10 months (as string): ', future_date_str)
Give Date: 1/21/2021 Date after 10 months: 2021-11-21 00:00:00 Date after 10 months: 2021-11-21 Date after 10 months (as string): 11/21/2021
We created a DateOffset object by passing months as 10. Then we added this DateOffset object to the datetime object. It returned a datetime object pointing to the another date i.e. after 10 months from the given date.
We learned about different ways to add months to a date in python.
Related posts:
Python time add month
Last updated: Feb 18, 2023
Reading time · 3 min
# Add months to a date in Python
Use the relativedelta class from the dateutil.relativedelta module to add months to a date in Python.
The relativedelta class automatically handles months with different numbers of days.
Copied!from datetime import date, datetime from dateutil.relativedelta import relativedelta date_1 = date(2023, 6, 24) print(date_1) # 👉️ 2023-06-24 # ✅ add 3 months to a date result = date_1 + relativedelta(months=+3) print(result) # 👉️ 2023-09-24
Make sure to import the relativedelta class and the date or datetime classes.
# Installing python-dateutil
If you don’t have the python-dateutil module installed, run the following command:
Copied!pip install python-dateutil # 👇️ or with pip3 pip3 install python-dateutil
The python-dateutil module provides extensions to the standard Python datetime module.
The example shows how to add months to a date object.
Copied!from datetime import date, datetime from dateutil.relativedelta import relativedelta date_1 = date(2023, 6, 24) print(date_1) # 👉️ 2023-06-24 result = date_1 + relativedelta(months=+3) print(result) # 👉️ 2023-09-24
Notice that we prefixed the number of months with a plus + to indicate that we want to add the specified number of months.
If necessary, the year will be rolled over automatically (e.g. adding 5 months to a date in November).
# Add months to the current date
If you need to add months to the current date, use the date.today() method.
Copied!from datetime import date, datetime from dateutil.relativedelta import relativedelta date_1 = date.today() print(date_1) # 👉️ 2023-07-21 result = date_1 + relativedelta(months=+2) print(result) # 👉️ 2023-09-21
The date.today method returns a date object that represents the current local date.
Make sure to import the relativedelta and date classes.
# Extracting the date after adding months
If you only need to extract the date after the operation, call the date() method on the datetime object.
Copied!from datetime import datetime from dateutil.relativedelta import relativedelta now = datetime.now() print(now) # 👉️ 2023-07-21 08:39:13.428040 result = now + relativedelta(months=+3) print(result) # 👉️ 2023-10-21 08:39:13.428040 # 👇️ only extract updated date print(result.date()) # 👉️ 2023-10-21
The datetime.date method returns a date object with the same year, month and day.
# Using a formatted-string literal to format the date
If you need to format the date in a certain way, use a formatted string literal.
Copied!from datetime import datetime from dateutil.relativedelta import relativedelta now = datetime.now() print(now) # 👉️ 2023-02-18 18:54:05.944818 result = now + relativedelta(months=+5) print(result) # 👉️ 2023-07-18 18:54:05.944818 # 👇️ only extract updated date print(result.date()) # 👉️ 2023-07-18 print(f'result:%Y-%m-%d %H:%M:%S>') # 👉️ 2023-07-18 18:54:05
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Make sure to wrap expressions in curly braces — .
Formatted string literals also enable us to use the format specification mini-language in expression blocks.
# Creating a datetime object from a date string and adding months
You can also create a datetime object from a date string and add months to it.
Copied!from datetime import datetime from dateutil.relativedelta import relativedelta my_str = '09-24-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-24 00:00:00 result = date_1 + relativedelta(months=+2) print(result) # 👉️ 2023-11-24 00:00:00
The datetime.strptime() method returns a datetime object that corresponds to the provided date string, parsed according to the format.
If you have a date string that is formatted in a different way, use this table of the docs to look up the format codes you should pass as the second argument to the strptime() method.
# Adding months to the current date using a datetime object
The following example adds months to the current date using a datetime object.
Copied!from datetime import datetime from dateutil.relativedelta import relativedelta date_1 = datetime.today() print(date_1) # 👉️ 2023-07-21 08:44:16.815774 result = date_1 + relativedelta(months=+3) print(result) # 👉️ 2023-10-21 08:44:16.815774
The datetime.today() method returns the current local date and time.
I’ve also written an article on how to add days to a date.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Add Month to datetime in Python
In Python, we can represent date values using the standard datetime library. We can store all the attributes of the date along with time attributes in datetime objects. The datetime objects can be manipulated with other libraries also like dateutil , pandas , and more.
We cannot directly add or subtract datetime objects and use the datetime.timedelta object to represent such intervals of time for an addition. However, this object cannot represent intervals of months, so we need to look for alternative methods.
Ways to add month to datetime in Python
Different methods on how to add months to datetime in Python are discussed below.
Using the datetime.datetime constructor to add month to datetime in Python.
The datetime.datetime constructor is used to initializing datetime objects in Python. This constructor accepts the month and other attributes for the date and time values.
We cannot directly overwrite such objects. We can just initialize the values at first and access them.
However, we can create our own function to create a new datetime object with updated values. We will use the values from the defined object and perform some calculations to create a new object.
In the above example, the add_mon() function creates a new datetime object after adding the months to a give datetime object.
Using the dateutil.relativedelta object to add month to datetime in Python
The dateutil module was developed to increase the functionalities of the standard datetime module. We can use functions from this module to work with datetime objects.
This module provides a relativedelta object to represent intervals of time, similar to the timedelta object of the datetime module. The difference between the two is that the former accepts a wide range of attributes (including months) and the latter has very few attributes.
Due to this, the relativedelta object can represent different intervals of time. We can use it to add months to datetime in Python.