I am trying to find the difference between two times using time module and then convert it to datetime format using strftime but I get a strange output for elapsed time starting from 1970, what is the best way to find elapsed time using python?
start_time = time()
info('My Start Time ' + datetime.fromtimestamp(start_time).strftime('%d-%m-%Y %H:%M:%S'))
sleep(5)
elapsed_time = time() - start_time
info('My Elapsed Time' + datetime.fromtimestamp(elapsed_time).strftime('%d-%m-%Y %H:%M:%S'))
Output is
[2016-03-17 00:45:16.828277] INFO: Generic: My Start Time 17-03-2016 11:45:16
[2016-03-17 00:45:21.832503] INFO: Generic: My Elapsed Time 01-01-1970 10:00:05
Time intervals are different to times. It doesn't really make sense to convert a time interval like elapsed_time
to a datetime
.
Your script can be simplified considerably by using the datetime
module's datetime
and timedelta
objects. When you subtract one datetime
from another the result is a timedelta
.
from time import sleep
from datetime import datetime
start_time = datetime.now()
print('My Start Time', start_time)
sleep(5)
stop_time = datetime.now()
print('My Stop Time', stop_time)
elapsed_time = stop_time - start_time
print('My Elapsed Time', elapsed_time)
output
My Start Time 2016-03-17 12:28:01.262090
My Stop Time 2016-03-17 12:28:06.265964
My Elapsed Time 0:00:05.003874
Please see the docs for timedelta
to see more examples of what you can do with these objects.
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