Skip to content

Instantly share code, notes, and snippets.

@risicle
Created March 17, 2016 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save risicle/0bfcafb9e43fe55cc22b to your computer and use it in GitHub Desktop.
Save risicle/0bfcafb9e43fe55cc22b to your computer and use it in GitHub Desktop.
import datetime
def apply_calendar_month_delta(datetime_in, month_delta):
"""
Applies an (integer) @month_delta to @datetime_in. Cheats on days, clamping them to (0,28] to avoid complexities.
>>> from datetime import date
>>> apply_calendar_month_delta(date(2014, 1, 3), -1)
datetime.date(2013, 12, 3)
>>> apply_calendar_month_delta(date(2014, 9, 3), 6)
datetime.date(2015, 3, 3)
>>> apply_calendar_month_delta(date(2011, 10, 31), 5)
datetime.date(2012, 3, 28)
>>> apply_calendar_month_delta(date(2012, 3, 25), -15)
datetime.date(2010, 12, 25)
"""
return datetime.date(year=datetime_in.year + (((datetime_in.month-1)+month_delta) // 12), month=(((datetime_in.month-1)+month_delta)%12)+1 , day=min(datetime_in.day, 28))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment