3

Given that I start with a string, like '3/6/2011' which is month/day/year, and the current day is 3/13/2011 (7 days later), how can I find the number of years that have passed since that time (7/365 = 0.0191780821917808) in Python?

Note that I want to be able to handle any input date. Not any format though, you can assume the format above.

Muhd
  • 24,305
  • 22
  • 61
  • 78

2 Answers2

11

You can get the timedelta by subtracting two datetimes, which gives you a lot of cool ways to operate on the time difference.

>>> import datetime
>>> before = datetime.datetime.strptime('3/6/2011','%m/%d/%Y')
>>> now = datetime.datetime.now()
>>> type(now-before)
<type 'datetime.timedelta'>
>>> (now-before).days
7
>>> float((now-before).days)/365
0.019178082191780823

EDIT: Wow, who would've thought there was so much depth to this simple question. Take a look at the answer with the most votes on this question. Dealing with leap years is a "hard" problem. (Credit to @kriegar)

Community
  • 1
  • 1
Chris W.
  • 37,583
  • 36
  • 99
  • 136
1
>>> import datetime
>>> datestring = "3/6/2011"
>>> (datetime.date.today() - datetime.datetime.strptime(datestring, "%m/%d/%Y").date()).days / 365.0
0.019178082191780823
Wooble
  • 87,717
  • 12
  • 108
  • 131