In this artilce, we will discuss different ways to subtract months from a given date in python.
Suppose we have a date ’21/1/2021′ and we want to subtract N months from it and N can be 1, 20, 50 or any other number. We want the final date after subtracting N months from the given date. Let’s see how to do that,
Subtract months from 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 subtract N months from a given date, create a relativedelta object representing the interval of N months and then subtract that from the datetime object to get the final date.
Steps to subtract N months from a date are as follows,
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: Subtract the relativedelta object from the datetime object. It will give us a datetime object point to a date i.e. N months before 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,
Subtract 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) # Subtract 20 months from a given datetime object n = 20 past_date = dtObj - relativedelta(months=n) print('Past Date: ', past_date) print('Past Date: ', past_date.date()) # Convert datetime object to string in required format past_date_str = past_date.strftime(date_format) print('Past Date as string object: ', past_date_str)
Give Date: 21/1/2021 Past Date: 2019-05-21 00:00:00 Past Date: 2019-05-21 Past Date as string object: 21/05/2019
We subtracted 20 months in the date ’21/1/2021′ to make it ’21/05/2019′.
As we subtracted relativedelta (of 20 months duration) from 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().
Subtract months from 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 subtract N months from a date.
Let’s understand with an example,
Subtract 10 months from 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) # Subtract 10 months from a given datetime object n = 10 past_date = dtObj - pd.DateOffset(months=n) print('Past Date: ', past_date) print('Past Date: ', past_date.date()) # Convert datetime object to string in required format past_date_str = past_date.strftime(date_format) print('Past Date as string object: ', past_date_str)
Give Date: 1/21/2021 Past Date: 2020-03-21 00:00:00 Past Date: 2020-03-21 Past Date as string object: 03/21/2020
We created a DateOffset object by passing months as 10. Then we subtracted this DateOffset object from the datetime object. It returned a datetime object pointing to the final date i.e. before 10 months from the given date.
We learned about different ways to subtract months from a date in python.
Pandas Tutorials -Learn Data Analysis with Python
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.