自 UTC 时区当天开始以来的秒数

发布于 2024-12-14 18:54:13 字数 75 浏览 7 评论 0原文

如何在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清风无影 2024-12-21 18:54:17
import time
t = time.gmtime()
seconds_since_utc_midnight = t.tm_sec + (t.tm_min * 60) + (t.tm_hour * 3600)

对于本地时间,我们可以使用 time.localtime() 而不是 time.gmtime()

import time
t = time.gmtime()
seconds_since_utc_midnight = t.tm_sec + (t.tm_min * 60) + (t.tm_hour * 3600)

for localtime, we can use time.localtime() instead of time.gmtime()

救星 2024-12-21 18:54:16

datetime.timedelta 中的秒数,xtimedelta.total_seconds

x.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:

x.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.

删除→记忆 2024-12-21 18:54:14

这是一种方法。

from datetime import datetime, time

utcnow = datetime.utcnow()
midnight_utc = datetime.combine(utcnow.date(), time(0))
delta = utcnow - midnight_utc
print delta.seconds # <-- careful

编辑 正如建议的,如果您想要微秒精度,或者可能跨越 24 小时周期(即 delta.days > 0),请使用 total_seconds() 或给定的公式作者:@unutbu。

print delta.total_seconds()  # 2.7
print delta.days * 24 * 60 * 60 + delta.seconds + delta.microseconds / 1e6 # < 2.7

Here's one way to do it.

from datetime import datetime, time

utcnow = datetime.utcnow()
midnight_utc = datetime.combine(utcnow.date(), time(0))
delta = utcnow - midnight_utc
print delta.seconds # <-- careful

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.

print delta.total_seconds()  # 2.7
print delta.days * 24 * 60 * 60 + delta.seconds + delta.microseconds / 1e6 # < 2.7
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文