肯定有更简单的方法。我有一些需要经常刷新的对象,所以我想记录它们创建的时间,检查当前的时间戳,并在必要时刷新。

datetime。datetime已被证明是困难的,我不想深入研究ctime库。这类事情还有更简单的吗?


当前回答

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

这对你有用吗?

其他回答

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

这对你有用吗?

这是一个对我有用的。

from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

希望这能有所帮助!

另一种方法是使用时间戳值:

end_time.timestamp() - start_time.timestamp()

如果你想计算两个已知日期之间的差值,可以像这样使用total_seconds:

import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0

我们在Python 2.7中有total_seconds()函数 请参阅下面的python 2.6代码

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)