In the example below I have generated two time values as a string that are in the format I wish using strftime
. I would like to subtract a
from b
to get c
. What is the missing line of code I need to do what I want?
import time
a = (time.strftime("%H:%M:%S"))
time.sleep(5)
b = (time.strftime("%H:%M:%S"))
c = b - a
print c
Thanks
Sounds like you're trying to find how much time is between two points. You should use datetime
objects for this (and in general in 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
In my test case (manually writing everything to a repr) I got
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