我有两个值。我认为某个操作将要花费的预期时间,以及完成该任务实际花费的时间值。在搜索解决方案时,我发现这个代码工作正常,直到任务花费的时间比预期的要长。
Expected = '00:00:20'
Actual = '00:00:25'
FMT = '%H:%M:%S'
Difference = datetime.strptime(Expected, FMT) - datetime.strptime(Actual, FMT)
print(Difference)
打印
-1 day, 23:59:55
所以我想知道如何将结果显示为-00:00:05而不是?
答案 0 :(得分:6)
只需3步即可完成:
编辑: 整个代码如下所示:
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="")