使用日期时间获取准确的纪元时间戳
我想要获得一天精确的(不是小时、分钟、秒)纪元时间戳,该时间戳在一天中保持不变。
这是精确到毫秒的(因此太准确了):
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
UNIX 时间戳必须精确到(毫秒)秒,因为它是一个计数秒的数字。您唯一能做的就是选择一个全天“保持不变”的特定时间,对于这个时间来说,午夜可能最有意义:
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:
这取决于你想要什么。
如果您只是想要一种快速的方法,请使用
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()
ortime.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).