使用日期时间获取准确的纪元时间戳

发布于 2025-01-12 04:20:16 字数 204 浏览 0 评论 0原文

我想要获得一天精确的(不是小时、分钟、秒)纪元时间戳,该时间戳在一天中保持不变。

这是精确到毫秒的(因此太准确了):

from datetime import date, datetime
timestamp = datetime.today().strftime("%s")

是否有任何简单的方法可以降低其精确度?

I want to get a day-accurate (not hour, minutes, seconds) Epoch timestamp that remains the same throughout the day.

This is accurate by the millisecond (and therefore too accurate):

from datetime import date, datetime
timestamp = datetime.today().strftime("%s")

Is there any simple way to make it less precise?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

聚集的泪 2025-01-19 04:20:16

UNIX 时间戳必须精确到(毫秒)秒,因为它是一个计数秒的数字。您唯一能做的就是选择一个全天“保持不变”的特定时间,对于这个时间来说,午夜可能最有意义:

from datetime import datetime, timezone

timestamp = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0).timestamp()

A UNIX timestamp is by necessity accurate to the (milli)second, because it's a number counting seconds. The only thing you can do is choose a specific time which "stays constant" throughout the day, for which midnight probably makes the most sense:

from datetime import datetime, timezone

timestamp = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
一杆小烟枪 2025-01-19 04:20:16

这取决于你想要什么。

如果您只是想要一种快速的方法,请使用 time.time_ns()time.time()。纪元时间由系统(在许多操作系统上)使用,因此没有转换。 _ns() 版本避免了浮点数学,因此速度更快。

如果你想以更有效的方式存储它,你可以这样做:
(int(time.time()) % (24*60*60) 这样你就可以在一天开始时获得纪元。与大多数其他时间(和 GPS 时间)相反,纪元有全天246060 秒(因此丢弃闰秒)。

It depends what do you want.

If you just want a quick way, either use time.time_ns() or time.time(). Epoch time is used by system (on many OS), and so there is no conversion. The _ns() version avoid floating point maths, so faster.

If you want to store it in more efficient way, you can just do a:
(int(time.time()) % (24*60*60) so you get the epoch at start of the day. Epoch contrary most of other times (and GPS time) has all days long 246060 seconds (so discarding leap seconds).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文