在下面的示例中,我生成了两个时间值作为字符串,其格式为我希望使用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
由于
答案 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