Skip to content

Instantly share code, notes, and snippets.

@shearichard
Created June 17, 2013 21:53
Show Gist options
  • Save shearichard/5800832 to your computer and use it in GitHub Desktop.
Save shearichard/5800832 to your computer and use it in GitHub Desktop.
Move backwards and forwards in month long chunks of time
def monthdelta(date, delta):
'''
Acts like datetime.timedelta but deals with months
`date`: A datetime object representing the base date
`delta`: An integer representing the offset (-ve for going back in time)
Found at : http://stackoverflow.com/a/3425124/364088
'''
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
if not m: m = 12
d = min(date.day, [31,
29 if y%4==0 and not y%400==0 else 28,31,30,31,30,31,31,30,31,30,31][m-1])
return date.replace(day=d,month=m, year=y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment