Python Forum
How to calculate time elapsed
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to calculate time elapsed
#1
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
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to calculate time difference between each row of dataframe in seconds Mekala 1 2,582 Jul-16-2020, 12:57 PM
Last Post: Larz60+
  Writing a function to calculate time range in Unix Epoch Time t4keheart 2 3,022 Jul-15-2020, 01:55 AM
Last Post: t4keheart
  How to assess elapsed time to execute a .exe file or opening a desktop application? Sudershan 2 2,148 Apr-18-2020, 01:40 PM
Last Post: buran
  How to calculate time in seconds rajeshE 1 2,112 Feb-15-2020, 11:07 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020