将日期转换为小时
我想找到两个日期之间的时差,然后比较差异时间(以小时为单位)。像这样的,
StartTime = 2011-03-10 15:45:48 EndTime = 2011-03-10 18:04:00
然后找到差异, 时间差=abs(开始时间-结束时间) 然后我需要将结果进行比较, 如果时间差> 6小时 ...
当我使用这种方法时,我得到的结果是时间格式,我应该如何在python中将时间格式更改为小时?
谢谢你,
I want to find time difference between two date and then compare the difference time in hours. Something like this,
StartTime = 2011-03-10 15:45:48
EndTime = 2011-03-10 18:04:00
And then find the difference as,
timeDifference = abs(StartTime - EndTime)
And then I need to compare the results as,
If timeDifference > 6 hours
...
When I use this method, the results I got was is in time format, how should I change time format into hours in python?
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您有两个日期和时间作为
datetime
对象(请参阅 datetime.datetime):将一个
datetime
与另一个datetime
相减,得到一个timedelta
对象,您可以使用abs
来确保时间差为正:现在,要将秒差从 timedelta 转换为小时,只需除以 3600:
请注意,total_seconds() 方法是在 Python 2.7 中引入的,因此如果您想要这样在早期版本中,您需要根据
.days
和.seconds
自行计算,如 这个答案更新: Jochen Ritzel 在下面的评论中指出,如果只是与几个小时进行比较,您感兴趣的是,而不是原始值,您可以通过以下方式更轻松地做到这一点:
Let's assume that you have your two dates and times as
datetime
objects (see datetime.datetime):Subtracting one
datetime
from another gives you atimedelta
object, and you can useabs
to ensure the time difference is positive:Now, to convert the seconds difference from a timedelta into hours, just divide by 3600:
Note that the
total_seconds()
method was introduced in Python 2.7, so if you want that on an earlier version, you'll need to calculate it yourself from.days
and.seconds
as in this answerUpdate: Jochen Ritzel points out in a comment below that if it's just the comparison with a number of hours that you're interested in, rather that the raw value, you can do that more easily with: