Get N Years, Months & Days Earlier as Certain datetime in Python (3 Examples)

In this article, I’ll show how to get X days, months, and years earlier as a certain datetime object in Python.

Creation of Example Data

We can load the datetime module as shown below.

import datetime                                  # Import datetime

For the following examples, we also need to import the relativedelta() function:

from dateutil.relativedelta import relativedelta

The data below will be used for the examples of this article.

x = datetime.datetime(2022, 4, 23, 9, 42, 30)    # Create datetime object
print(x) 
# 2022-04-23 09:42:30

Example 1: Subtract N Years from datetime object

To subtract a certain amount of years from our datetime object, we can use the relativedelta() function in combination with the years argument.

x_years = x - relativedelta(years = 3)           # Get date 3 years ago
print(x_years)
# 2019-04-23 09:42:30

Example 2: Subtract N Months from datetime object

To get the datetime a specific number of months ago from our example data, we use the relativedelta() function together with the months argument.

x_months = x - relativedelta(months = 7)         # Get date 7 months ago
print(x_months)
# 2021-09-23 09:42:30

Example 3: Subtract N Days from datetime object

And for subtracting a certain amount of days from our datetime object, we simply use the relativedelta() function combined with the days argument.

x_days = x - relativedelta(days = 15)            # Get date 15 days ago
print(x_days)
# 2022-04-08 09:42:30

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top