关于datetime:计算Python中的时间跨度

Calculate time span in Python

我在Windows 64bit上使用Python v2.x.

我想实时记录两个时刻并计算时间跨度。
请参阅以下代码:

1
2
3
4
5
6
7
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不是整数,所以我的问题是,如何将此语句转换为整数来进行数学运算? 转换为秒是我的第一个想法......


1
2
3
4
5
current_time1 = datetime.datetime.now()
time.sleep(50)
current_time2 = datetime.datetime.now()

print (current_time2 - current_time1)

或者

1
2
3
4
time1 = time.time()
time.sleep(50)
time2 = time.time()
print("%s seconds"%(time2-time1))


从另一个中减去一个datetime.datetime.now()会得到一个datetime.timedelta实例。 如果在其上运行dir(),您可能会发现一些有用的功能。

1
2
3
4
5
6
7
8
9
10
>>> 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


1
2
3
4
5
6
import time

current_time1 = time.clock()
do_something()
current_time2 = time.clock()
print"%.2gs" % (current_time2-current_time1)

编辑:

1
2
3
from datetime import datetime, date

datetime.combine(date.today(), current_time2) - datetime.combine(date.today(), current_time1)