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
  • 22,609
  • 22
  • 60
  • 76

3 Answers3

9

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.
  • 34,983
  • 34
  • 91
  • 128
1
>>> import datetime
>>> datestring = "3/6/2011"
>>> (datetime.date.today() - datetime.datetime.strptime(datestring, "%m/%d/%Y").date()).days / 365.0
0.019178082191780823
Wooble
  • 84,802
  • 12
  • 102
  • 128
1

All the answers above don't take into account leap years. And it looks like this question has discussion that is relevant to your question.

Pythonic difference between two dates in years?

Community
  • 1
  • 1
dting
  • 37,400
  • 9
  • 92
  • 114
  • 1
    To be fair, he did ask in his question for the `x/365` answer. – Chris W. Mar 14 '11 at 03:27
  • +1 but i wanted to make the point that fractional years using 365 is fishy – dting Mar 14 '11 at 03:29
  • Excellent point. And after reading your link, it's clear that that is a much harder problem than it would seem at first--basically because we think of "years" to be a very consistent measurement of time, but actually its variable depending on which year you're talking about. – Chris W. Mar 14 '11 at 03:38