In this post we will be creating a Python script that will subtract a given number of months from a date. In this example we will not have to worry about the number of days in each month i.e. the handling of 28, 30 and 31 days of a particular month.
To help us achieve this we will be using the dateutil module which acts as an extension to the standard datetime module.
To install the dateutil module run the following command.
pip install python-dateutil
In particular we will utilize relativedelta, see the snippet of Python code below which will subtract three months from todays date.
from datetime import date from dateutil.relativedelta import relativedelta three_months = date.today() + relativedelta(months=-3) print(three_months)
The above would return the current date subtracted by three months.
Similarly, we can adapt the above code to add months to the date instead. See the sample of code below that will add three months.
from datetime import date from dateutil.relativedelta import relativedelta three_months = date.today() + relativedelta(months=+3) print(three_months)
The above would return the date exactly three month ahead of the current date.
Take a look at some of our other content around the Python programming language here.