从另一个中减去一个strftime字符串

时间:2016-01-28 23:56:12

标签: python strftime

在下面的示例中,我生成了两个时间值作为字符串,其格式为我希望使用strftime。我想从a中减去b以获得c。我需要做什么缺少我需要的代码?

import time

a = (time.strftime("%H:%M:%S"))

time.sleep(5)

b = (time.strftime("%H:%M:%S"))

c = b - a

print c

由于

1 个答案:

答案 0 :(得分:3)

听起来你正试图找出两点之间的时间。您应该使用datetime对象(通常在Python中使用!)

import datetime
import time

before = datetime.datetime.now()  # don't convert to string!

time.sleep(5)  # do some stuff....

after = datetime.datetime.now()

delta = after - before
# delta is a datetime.timedelta object.

print(delta)
# which by default stringifies to %H:%M:%S.%f

在我的测试用例中(手动将所有内容写入repr)我得到了

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> before = datetime.datetime.now()
>>> after = datetime.datetime.now()
>>> delta = after - before
>>> print(delta)
0:00:05.239524