如何检查两个日期之间的差异(以秒为单位)?
必须有一种更简单的方法来做到这一点。我有一些需要经常刷新的对象,因此我想记录它们的创建时间,检查当前时间戳,并根据需要刷新。
datetime.datetime 已被证明很困难,我不想深入研究 ctime 库。对于这种事情,还有什么更容易的事情吗?
There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary.
datetime.datetime has proven to be difficult, and I don't want to dive into the ctime library. Is there anything easier for this sort of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您想计算两个已知日期之间的差异,请使用
total_seconds
,如下所示:86400.0
0
if you want to compute differences between two known dates, use
total_seconds
like this:86400.0
0
这对你有用吗?
would that work for you?
(7 将是您在上面等待的时间)
我发现 datetime.datetime 相当有用,因此如果您遇到了复杂或尴尬的情况,请告诉我们。
编辑:感谢@WoLpH 指出,人们并不总是需要频繁刷新以使日期时间接近。通过考虑增量中的天数,您可以处理更长的时间戳差异:
(7 will be whatever amount of time you waited a bit above)
I find datetime.datetime to be fairly useful, so if there's a complicated or awkward scenario that you've encountered, please let us know.
EDIT: Thanks to @WoLpH for pointing out that one is not always necessarily looking to refresh so frequently that the datetimes will be close together. By accounting for the days in the delta, you can handle longer timestamp discrepancies:
我们在 Python 2.7 中有函数total_seconds()
请参阅下面的 python 2.6 代码
We have function total_seconds() with Python 2.7
Please see below code for python 2.6
这是为我工作的一个。
希望这有帮助!
Here's the one that is working for me.
Hope this helps!
另一种方法是使用时间戳值:
Another approach is to use timestamp values:
通过阅读源码,我得出一个结论:通过
.seconds
无法获取时间差:By reading the source code, I came to a conclusion: the time difference cannot be obtained by
.seconds
:total_seconds can get an accurate difference between the two times
in conclusion: