Search code examples
pythonstringdatetimetimestring-conversion

Python: Get number of years that have passed from date string


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.


Solution

  • 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)