Pythons datetime functions are indeed quite unhandy sometimes. While you can use datetime.timedelta
objects for your case, to substract times in days, e.g. upcounting month or years becomes annoying. So in case you sooner or later not only want to add one day, maybe give this function a try:
import datetime
import calendar
def upcount(dt, years=0, months=0, **kwargs):
"""
Python provides no consistent function to add time intervals
with years, months, days, minutes and seconds. Usage example:
upcount(dt, years=1, months=2, days=3, hours=4)
"""
if months:
total_months = dt.month + months
month_years, months = divmod(total_months, 12)
if months == 0:
month_years -= 1
months = 12
years += month_years
else:
months = dt.month
years = dt.year + years
try:
dt = dt.replace(year=years, month=months)
except ValueError:
# 31st march -> 31st april gives this error
max_day = calendar.monthrange(years, months)[1]
dt = dt.replace(year=years, month=months, day=max_day)
if kwargs:
dt += datetime.timedelta(**kwargs)
return dt