Pythonic difference between two dates in years?

后端 未结 12 2514
醉酒成梦
醉酒成梦 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:09

    If you want precise results, I recommend using the dateutil library.

    from dateutil.relativedelta import relativedelta
    difference_in_years = relativedelta(end_date, start_date).years
    

    This is for complete years (e.g. a person's age). If you want fractional years, then add months, days, hours, ... up to the desired precision.

提交回复
热议问题