我在Windows 64bit上使用Python v2.x
我想实时记录两个时刻并计算时间跨度。 请参阅以下代码:
current_time1 = datetime.datetime.now().time() # first moment
# ... some statement...some loops...take some time...
current_time2 = datetime.datetime.now().time() # second moment
time_span = current_time1 - current_time2
显然最后一行不可执行,因为current_time不是整数,所以我的问题是,如何将此语句转换为整数来进行数学运算?转换为秒是我的第一个想法...
答案 0 :(得分:3)
current_time1 = datetime.datetime.now()
time.sleep(50)
current_time2 = datetime.datetime.now()
print (current_time2 - current_time1)
或者
time1 = time.time()
time.sleep(50)
time2 = time.time()
print("%s seconds"%(time2-time1))
答案 1 :(得分:1)
import time
current_time1 = time.clock()
do_something()
current_time2 = time.clock()
print "%.2gs" % (current_time2-current_time1)
编辑:
from datetime import datetime, date
datetime.combine(date.today(), current_time2) - datetime.combine(date.today(), current_time1)
答案 2 :(得分:1)
从另一个中减去一个datetime.datetime.now()
会为您提供datetime.timedelta
个实例。如果您在其上运行dir()
,您可能会发现一些有用的功能。
>>> x = datetime.datetime.now()
# wait a second or two or use time.sleep()
>>> y = datetime.datetime.now()
>>> z = y - x
>>> type(z)
<type 'datetime.timedelta'>
>>> print(list(filter(lambda x: not x.startswith("_"), dir(z))))
['days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']
>>> print(z.total_seconds())
2.31
答案 3 :(得分:0)
在python 3.x中,使用time.perf_counter
import time
t1_start = time.perf_counter()
do_something() # your code goes here
t1_stop = time.perf_counter()
print("Elapsed time:", t1_stop - t1_start) # print performance indicator