自 UTC 时区当天开始以来的秒数
如何在Python中找到“自UTC时区开始以来的秒数”?我查看了文档,但不明白如何使用 datetime.timedelta 来获取它。
How do I find "number of seconds since the beginning of the day UTC timezone" in Python? I looked at the docs and didn't understand how to get this using datetime.timedelta
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于本地时间,我们可以使用
time.localtime()
而不是time.gmtime()
for localtime, we can use
time.localtime()
instead oftime.gmtime()
datetime.timedelta
中的秒数,x
由 timedelta.total_seconds:该函数在Python2.7中引入。对于旧版本的 python,您只需自己计算:
total_seconds = x.days*24*60*60 + x.seconds + x.microseconds/1e6
。The number of seconds in a
datetime.timedelta
,x
, is given by timedelta.total_seconds:This function was introduced in Python2.7. For older versions of python, you just have to compute it yourself:
total_seconds = x.days*24*60*60 + x.seconds + x.microseconds/1e6
.这是一种方法。
编辑 正如建议的,如果您想要微秒精度,或者可能跨越 24 小时周期(即 delta.days > 0),请使用
total_seconds()
或给定的公式作者:@unutbu。Here's one way to do it.
EDIT As suggested, if you want microsecond precision, or potentially crossing a 24-hour period (i.e. delta.days > 0), use
total_seconds()
or the formula given by @unutbu.