Python 3 - calculating the difference between two time values

I have two meanings. The expected amount of time that I think the action will take, and the value of how long it really took to complete this task. When searching for a solution, I found this code that works until the task takes longer than expected.

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

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

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

print(Difference)

Will print

-1 day, 23:59:55

So, I was wondering, how can I get a result that will display as -00: 00: 05 instead?

+4
source share
1 answer

Just do it in 3 steps:

  • step: Compare 2 times
  • step: subtract the smaller from the larger.
  • step: 2., , .

EDIT: :

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="")
+6

Source: https://habr.com/ru/post/1687740/


All Articles