Home > other >  Can't get the real time difference between two times in hours
Can't get the real time difference between two times in hours

Time:01-29

When I run this code it works fine, but it gives me the wrong time difference

import datetime

start_time = "02:30 PM"
end_time = "01:30 AM"

firstTime = datetime.datetime.strptime(start_time , "%I:%M %p")
print(f"Datetime Start Time is {firstTime}")

endTime = datetime.datetime.strptime(end_time , "%I:%M %p")
print(f"Datetime End Time Is {endTime}")

deltaTime = firstTime-endTime

print(f"Time Difference is {deltaTime.total_seconds()/(60*60)} hours")

When I check the time difference in google it says 11 hours, but this code returns 13 hours why is that?

CodePudding user response:

The code is correct.

It will calculate form the same day. Since you have not mentined the start day.

Datetime Start Time is 1900-01-01 14:30:00
Datetime End Time Is 1900-01-01 01:30:00
Time Difference is 13.0 hours

So, when you take the difference between 01:30 and 14:30 on the same day that is 1900-01-01 the difference will be 13 hours as 01:30 comes before 14:30

CodePudding user response:

I think it might have to do with your subtraction deltaTime = firstTime-endTime

Basically if count from the endTime to firstTime it's doing a 14:30 - 1:30 instead of doing a 1:30 - 14:30

I suggest you change the order of the math count and then format the answer because the value of deltaTime will be -1 day, 11:00:00

CodePudding user response:

I think you can handle that by adding a simple (if.. else) statement with datetime.timedetla to shift the difference by one day in case your end_time falls on the next day.

deltaTime = endTime - firstTime

timeDiff = deltaTime   timedelta(days=1) if deltaTime.days < 0 else deltaTime

Output :

print(f"Time difference is {timeDiff.total_seconds()/3600} hours")
#Time difference is 11.0 hours
  • Related