Python - Date & Time Comparison using timestamps, timedelta

霸气de小男生 提交于 2019-11-30 17:13:10
murgatroid99

You should be able to use

tdelta.total_seconds()

to get the value you are looking for. This is because tdelta is a timedelta object, as is any difference between datetime objects.

A couple of notes:

  1. Using strftime followed by strptime is superfluous. You should be able to get the current datetime with datetime.now.
  2. Similarly, using time.ctime followed by strptime is more work than needed. You should be able to get the other datetime object with datetime.fromtimestamp.

So, your final code could be

now = datetime.now()
then = datetime.fromtimestamp(os.path.getmtime("x.cache"))
tdelta = now - then
seconds = tdelta.total_seconds()

What's wrong with this method?

>>> from datetime import datetime
>>> a = datetime.now()
>>> b = datetime.now() # after a few seconds
>>> delta = a-b
>>> delta.total_seconds()
-6.655989

Note that total_seconds is only available in Python 2.7 <, but per the documentation is:

Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.

which yields the exact same result.

MHardy

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())))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!