Python - Date & Time Comparison using timestamps, timedelta

前端 未结 3 1784
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 20:46

I\'ve spent the past hour digging around the Python docs and many SO questions; please forgive me for being another Python newbie trapped by the mystery of time difference i

3条回答
  •  旧时难觅i
    2021-01-03 21:23

    I had the same problem couple of months ago. What you are looking for is datetime.timedelta and datetime.datetime.fromtimestamp(). Here is an example for how to use them to fix your problem.

    import datetime
    import time
    t1 = time.time()
    #do something to kill time or get t2 from somewhere
    a = [i for i in range(1000)]
    t2 = time.time()
    #get the difference as datetime.timedelta object
    diff=(datetime.datetime.fromtimestamp(t1) - datetime.datetime.fromtimestamp(t2))
    #diff is negative as t2 is in the future compared to t2
    print('difference is {0} seconds'.format(abs(diff.total_seconds())))
    

提交回复
热议问题