The easiest way to subtract years from a date in Python is to use the dateutil extension.
Install it with pip:
pip install python-dateutil
The relativedelta
object from the dateutil.relativedelta
module allows you to subtract any number of years from a date object.
In this example I always take the current date using the date.today()
method.
Then I set a relativedelta
of 2 years and subtract it from current_date
.
from datetime import date
from dateutil.relativedelta import relativedelta
current_date = date.today()
print(current_date)
future_date = current_date - relativedelta(years=2)
print(future_date)
2022-02-15
2020-02-15
You can also check: