我在 Windows 64 位上使用 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
Run Code Online (Sandbox Code Playgroud)
显然最后一行是不可执行的,因为 current_time 不是整数,所以我的问题是,如何将此语句转换为整数来进行数学运算?转换为秒是我的第一个想法......
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
Run Code Online (Sandbox Code Playgroud)