Answers:
如果要计算两个已知日期之间的差异,请使用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
(b-a).microseconds
然后除以秒(1000000)或毫秒(1000)
-60
:from datetime import datetime; (datetime(2019, 1, 1, 0, 0) - datetime(2019, 1, 1, 0, 1)).total_seconds()
import time
current = time.time()
...job...
end = time.time()
diff = end - current
那对你有用吗?
>>> from datetime import datetime
>>> a = datetime.now()
# wait a bit
>>> b = datetime.now()
>>> d = b - a # yields a timedelta object
>>> d.seconds
7
(7将是您在上面等待的时间长短)
我发现datetime.datetime非常有用,因此,如果您遇到了复杂或尴尬的情况,请告诉我们。
编辑:感谢@WoLpH指出,人们不一定总是希望刷新得如此频繁,以至于日期时间会接近。通过考虑增量中的天数,您可以处理更长的时间戳差异:
>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800
d.seconds + d.days * 86400
,则可以在多天内改正;)
a - b
:在之前a
是(即结果为负):while 。我相信正确的方法是使用…但这仅是py2.7 +。 b
(a - b).seconds == 86282
a - b == datetime.timedelta(-1, 86276, 627665)
timedelta.total_seconds()
timedelta.total_seconds()
。相应地降低了票数。
total_seconds()
是2.7+的功能。
我们在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)
这是为我工作的人。
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;
希望这可以帮助!