用Python计算时间跨度

2024-05-12 12:55:47 发布

您现在位置:Python中文网/ 问答频道 /正文

im在64位Windows上使用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

显然最后一行是不可执行的,因为当前时间不是整数,所以我的问题是,如何将此语句转换为整数来进行计算?转换成秒是我的第一个想法。。。


Tags: 代码datetimetimewindows记录整数somecurrent
3条回答
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)

从另一个实例中减去一个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
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))

相关问题 更多 >