How can I produce a human readable difference when subtracting two UNIX timestamps using Python?

后端 未结 7 1009
無奈伤痛
無奈伤痛 2020-12-23 19:39

This question is similar to this question about subtracting dates with Python, but not identical. I\'m not dealing with strings, I have to figure out the difference between

7条回答
  •  攒了一身酷
    2020-12-23 20:11

    You can use the wonderful dateutil module and its relativedelta class:

    import datetime
    import dateutil.relativedelta
    
    dt1 = datetime.datetime.fromtimestamp(123456789) # 1973-11-29 22:33:09
    dt2 = datetime.datetime.fromtimestamp(234567890) # 1977-06-07 23:44:50
    rd = dateutil.relativedelta.relativedelta (dt2, dt1)
    
    print "%d years, %d months, %d days, %d hours, %d minutes and %d seconds" % (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds)
    # 3 years, 6 months, 9 days, 1 hours, 11 minutes and 41 seconds
    

    It doesn't count weeks, but that shouldn't be too hard to add.

提交回复
热议问题