我不知道内置方法。但它可以很容易地手动完成:
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)
演示:
>>> d = date(2020, 12, 10)
>>> add_month(d, 3)
datetime.date(2021, 3, 10)
>>> add_month(d, -13)
datetime.date(2019, 11, 10)
它甚至可以处理更短的月份:
>>> d =date(2017,1,30)
>>> add_month(d, 1)
datetime.date(2017, 2, 28)