im using Python v2.x on Windows 64bit
I would like to record two moments in real time and calculate the time span. Please see code as following:
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
Apparently the last line is not executable because current_time is not integer, so my question is, how to convert this statement to integer to do the math? Convert to seconds is my first thought...
Subtracting a one datetime.datetime.now() from another gives you a datetime.timedelta instance. If you run dir() on it, you will likely find some useful functions.
>>> 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)
or alternatively
time1 = time.time()
time.sleep(50)
time2 = time.time()
print("%s seconds"%(time2-time1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With