Python: get datetime for '3 years ago today'
Subtracting 365*3 days is wrong, of course--you're crossing a leap year more than half the time.
dt = datetime.now()
dt = dt.replace(year=dt.year-3)
# datetime.datetime(2008, 3, 1, 13, 2, 36, 274276)
ED: To get the leap-year issue right,
def subtract_years(dt, years):
try:
dt = dt.replace(year=dt.year-years)
except ValueError:
dt = dt.replace(year=dt.year-years, day=dt.day-1)
return dt
import datetime
datetime.datetime.now() - datetime.timedelta(days=3*365)
def add_years(dt, years):
try:
result = datetime.datetime(dt.year + years, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
except ValueError:
result = datetime.datetime(dt.year + years, dt.month, dt.day - 1, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)
return result
>>> add_years(datetime.datetime.now(), -3)
datetime.datetime(2008, 3, 1, 12, 2, 35, 22000)
>>> add_years(datetime.datetime(2008, 2, 29), -3)
datetime.datetime(2005, 2, 28, 0, 0)
If you need to be exact use the dateutil module to calculate relative dates
from datetime import datetime
from dateutil.relativedelta import relativedelta
three_yrs_ago = datetime.now() - relativedelta(years=3)