Skip to content

Instantly share code, notes, and snippets.

@ecarreras
Created December 7, 2012 12:58
Show Gist options
  • Select an option

  • Save ecarreras/4233105 to your computer and use it in GitHub Desktop.

Select an option

Save ecarreras/4233105 to your computer and use it in GitHub Desktop.
def delta_months(date, months):
sign = months / abs(months)
current_day = date.day
date -= timedelta(current_day)
while months:
month_days = calendar.monthrange(date.year, date.month)[1]
date += timedelta(month_days * sign)
months += sign * -1
if current_day > month_days:
current_day = month_days
return date + timedelta(days=current_day)
def delta_months2(date, months):
sign = months / abs(months)
year, month = divmod(months, 12)
m = [x % 13 for x in range(12, 25) if x % 13]
newmonth = m[(date.month + month) % 12]
newyear = date.year + year * sign
newday = date.day
month_days = calendar.monthrange(newyear, newmonth)[1]
if date.day > month_days:
newday = month_days
return date.replace(year=newyear, month=newmonth, day=newday)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment