Pythonic difference between two dates in years?

后端 未结 12 2476
醉酒成梦
醉酒成梦 2020-12-02 16:21

Is there a more efficient way of doing this below? I want to have the difference in years between two dates as a single scalar. Any suggestions are welcome.

         


        
12条回答
  •  时光取名叫无心
    2020-12-02 17:18

    More efficient? No, but more correct, probably. But it depends on how correct you want to be. Dates are not trivial things.

    Years do not have a constant length. Do you want the difference in leap years or normal years? :-) As you calculate you are always going to get a slightly incorrect answer. And how long is a day in years? You say 1/365.2425. Well, yeah, averaged over a thousand years, yeah. But otherwise not.

    So the question doesn't really make much sense.

    To be correct you have to do this:

    from datetime import datetime
    from calendar import isleap
    start_date = datetime(2005,4,28,12,33)
    end_date = datetime(2010,5,5,23,14)
    diffyears = end_date.year - start_date.year
    difference  = end_date - start_date.replace(end_date.year)
    days_in_year = isleap(end_date.year) and 366 or 365
    difference_in_years = diffyears + (difference.days + difference.seconds/86400.0)/days_in_year
    

    In this case that's a difference of 0.0012322917425568528 years, or 0.662 days, considering that this is not a leap year.

    (and then we are ignoring microseconds. Heh.)

提交回复
热议问题