Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get datetime for '3 years ago today'

In Python, how do I get a datetime object for '3 years ago today'?

UPDATE: FWIW, I don't care hugely about accuracy... i.e. it's Feb 29th today, I don't care whether I'm given Feb 28th or March 1st in my answer. Concision is more important than configurability, in this case.

like image 978
AP257 Avatar asked Mar 01 '11 17:03

AP257


2 Answers

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) 
like image 77
Vince Spicer Avatar answered Sep 22 '22 03:09

Vince Spicer


import datetime datetime.datetime.now() - datetime.timedelta(days=3*365) 
like image 31
Fábio Diniz Avatar answered Sep 18 '22 03:09

Fábio Diniz