本文介绍了在Python中计算时间(datetime.timedelta?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这是很多人的一个nobrainer,但我觉得我真的很困惑与整个datetime.timedelta的事情。实际上,当我开始 startTime 时,我会记录一些时间戳,然后我对进程的结束进行时间戳记 endTime ,我试图获取HH:MM:SS的差异,我没有运气。

I am sure this is a nobrainer for a lot of you, but I find myself really confused with the whole datetime.timedelta thing. Essentially I timestamp something when I start startTime and then I timestamp the end of the process endTime and I am trying to get the difference in HH:MM:SS and am having no luck.

我打印时收到此错误 endTime - startTime

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

已修改为包含最终结果:

Edited to include final result:

startTime = datetime.now()
<... my looping process ...>
endTime = datetime.now()
calcdTime = endTime - startTime
print str(calcdTime)[:-4]

输出为:H:MM:SS.MM(从而剥离 timedelta之前的最后4个字符

This outputs to: H:MM:SS.MM (thus stripping the last 4 characters off the timedelta

推荐答案

使用 datetime 而不是 code>。从另一个减去一次是无意义的,没有日期;你不能只假设他们在同一天,左操作数先到。

Use a datetime instead of a time. Subtracting one time from another is meaningless without a date; you can't just assume that they're on the same day and the left operand comes first.

这篇关于在Python中计算时间(datetime.timedelta?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:20