简体   繁体   中英

Python 3 - Calculating the difference between two time values

I have two values. An expected amount of time that I think an action is going to take, and a value of how long it actually took to complete that task. When searching for a solution I found this code that works fine up until the task took longer to finish than what was expected.

Expected = '00:00:20'
Actual = '00:00:25'

FMT = '%H:%M:%S'

Difference = datetime.strptime(Expected, FMT) - datetime.strptime(Actual, FMT)

print(Difference)

This prints

-1 day, 23:59:55

So I was wondering how I can get the result to show up as -00:00:05 instead?

Just do it in 3 steps:

  1. step: Compare the 2 time values
  2. step: Subtract the smaller one from the bigger one
  3. step: If you needed to reverse the order of the numbers in the 2. step, then you have a negative amount of time, otherwise the difference is positive.

EDIT: The whole code looks like this:

from datetime import datetime
Expected = '00:00:20'
Actual = '00:00:25'

FMT = '%H:%M:%S'

time1=datetime.strptime(Expected, FMT)
time2=datetime.strptime(Actual, FMT)
rev=time1<time2
Difference =  time2 - time1 if rev else time1-time2
print("-" if rev else "",Difference,sep="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM