I know no builtin way. But it can easily done by hand:
def add_year(dt, years):
"""
Add years years to dt and return the new value.
dt can be a date or datetime, years must be an integer value (may be negative)
"""
try:
return dt.replace(year=dt.year + years)
except ValueError:
# the day that does not exist in new month: return last day of month
return dt.replace(year=dt.year + years, month=dt.month + 1, day=1
) - timedelta(days=1)
def add_month(dt, months):
"""
Add months months to dt and return the new value.
dt can be a date or datetime, months must be an integer value (may be negative)
"""
y, m = divmod(months + dt.month, 12)
try:
return dt.replace(year=dt.year + y, month=m)
except ValueError:
# the day that does not exist in new month: return last day of month
return dt.replace(year=dt.year + y, month=m + 1, day=1
) - timedelta(days=1)
Demo:
>>> d = date(2020, 12, 10)
>>> add_month(d, 3)
datetime.date(2021, 3, 10)
>>> add_month(d, -13)
datetime.date(2019, 11, 10)
It even handles shorter months:
>>> d =date(2017,1,30)
>>> add_month(d, 1)
datetime.date(2017, 2, 28)
30 daysto lets say, jan, to get output as feb ?