Using datetime.timedelta to add years
You can hard code a new year value of the datetime using replace instead :)
This avoids leap years etc.
year_later = current.replace(year=current.year + 1)
Note that if the current date happens to be the 29th of February, this will raise a ValueError
with the message: "Day is out of range for month". So you need to handle this special case, like this:
if current.month == 2 and current.day == 29:
year_later = current.replace(year=current.year + 1, day=28)
else:
year_later = current.replace(year=current.year + 1)
timedelta
does not support years, because the duration of a year depends on which year (for example, leap years have Feb 29).
You could use a relativedelta
instead (from PyPI package python-dateutil
) which does support years
and takes into account the baseline date for additions.
>>> from dateutil.relativedelta import relativedelta
>>> import datetime
>>> d = datetime.date(2020, 2, 29)
>>> d
datetime.date(2020, 2, 29)
>>> d + relativedelta(years=1)
datetime.date(2021, 2, 28)
My quick and dirty method is to use
y = [number of years]
timedelta(days= y * 365)
I found this question looking for a more elegant solution. For my uses a precise answer wasn't necessary. I don't mind losing a day each leap year in this particular case.