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 |
import datetime # Import datetime
For the following examples, we also need to import the relativedelta() function:
from dateutil.relativedelta import relativedelta |
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 |
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 |
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 |
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 |
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.
- How to Add Days, Months & Years to a datetime Object in Python (3 Examples)
- Add Hours, Minutes & Seconds to datetime Object in Python (3 Examples)
- Get Time Difference Between Two Dates & Times in Python (datetime Module)
- Get Year, Month & Day Separately from datetime Object in Python (3 Examples)
- All Python Programming Tutorials
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.