i know using datetime.timedelta i can get the date of some days away form given date
daysafter = datetime.date.today() + datetime.timedelta(days=5)
I often need to need to keep the date as last in month when adding months. I try to add the amount of months to the day after and then remove one day again. If that fails I add one more day until success.
from datetime import timedelta
DAY = timedelta(1)
def add_months(d, months):
"Add months to date and retain last day in month."
d += DAY
# calculate year diff and zero based month
y, m = divmod(d.month + months - 1, 12)
try:
return d.replace(d.year + y, m + 1) - DAY
except ValueError:
# on fail return last day in month
# can't fail on december so just adding one more month
return d.replace(d.year + y, m + 2, 1) - DAY