Python Forum
How to calculate time elapsed - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to calculate time elapsed (/thread-10592.html)



How to calculate time elapsed - SriRajesh - May-26-2018

Hi,

I want to calculate time elapsed between two times intervals

s3 = '11:22:26'
s4= '01:22:26'
FMT = '%H:%M:%S'
tdelta3 = datetime.strptime(s4, FMT) - datetime.strptime(s3, FMT)
But I get wrong time as below:
print (tdelta3)
-1 day, 14:00:00


RE: How to calculate time elapsed - killerrex - May-26-2018

You are getting the correct result, it is just that the timedelta object stores the information keeping always the number of seconds and microseconds positive.

So for a timedelta of -10 hours, it really stores a delta of -1 day + 14 hours = -24+14=-10 hours.
This might look strange but is really handy when dealing with dates.
If you want to know the period of time, with negative values as usual you can use the total_seconds:
>>> tdelta3.total_seconds()
-36000.0
And if you want it in other unit like for example number of hours it represents:
>>> tdelta3 / timedelta(hours=1)
-10.0
Is just the same as dividing by 3600 but with less magic numbers and you can use unusual things like 1 day and 3 hours with timedelta(days=1, hours=3), that is much better than a mysterious 97200 hardcoded in your code.