简体   繁体   English

在 Python (datetime.timedelta?) 中计算时间

[英]Calculating Time in Python (datetime.timedelta?)

I am sure this is a nobrainer for a lot of you, but I find myself really confused with the whole datetime.timedelta thing.我相信这对你们中的很多人来说是一件轻而易举的事,但我发现自己对整个 datetime.timedelta 事情感到非常困惑。 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.本质上,我在开始startTime时为某些东西加上时间戳,然后在进程endTime结束时加上时间戳,我试图获得 HH:MM:SS 的差异并且没有运气。

I get this error when I do print endTime - startTime :当我打印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]

This outputs to: H:MM:SS.MM (thus stripping the last 4 characters off the timedelta这输出到: H:MM:SS.MM (从而从timedelta中剥离最后 4 个字符

Use a datetime instead of a time .使用datetime而不是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.您不能只假设它们在同一天并且左操作数排在第一位。

Depending on what you're doing with the information, you might want to just use time.time :根据您对信息的处理方式,您可能只想使用time.time

import time

starttime = time.time()

# do stuff

endtime = time.time()

elapsed = endtime - starttime
print elapsed

Which will give you the elapsed time in seconds.这将为您提供以秒为单位的经过时间。 This is often more convenient than having a timedelta .这通常比使用timedelta更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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