Skip to content

Instantly share code, notes, and snippets.

@adamjforster
Created December 13, 2010 15:46
Show Gist options
  • Save adamjforster/739119 to your computer and use it in GitHub Desktop.
Save adamjforster/739119 to your computer and use it in GitHub Desktop.
A simple fuction to subtract a number of years from a date.
import calendar
import datetime
def subtract_years(date, years):
"""Subtract a number of years from a given date.
>>> d = datetime.date(year=2012, month=2, day=29)
>>> subtract_years(d, 1)
datetime.date(2011, 2, 28)
>>> subtract_years(d, 4)
datetime.date(2008, 2, 29)
"""
year = date.year - years
month = date.month
day = date.day
if month == 2 and day > 28:
if not calendar.isleap(year):
day = 28
return datetime.date(year=year, month=month, day=day)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment