【问题标题】:Python embedded. timestamp() return same time over multiple seconds嵌入 Python。 timestamp() 在多秒内返回同一时间
【发布时间】:2021-02-25 16:35:21
【问题描述】:

我已经实现了一个回调系统。我想在调用函数时以 unix epoch 显示时间。

例如:

from datetime import datetime

def my_callback():
    print(datetime.now().timestamp())
    print(datetime.now())

在游戏中:

First call:
1614270080.0
2021-02-25 19:22:14.304776

Second call after a second:
1614270080.0
2021-02-25 19:22:15.498516

Last call after a 2 seconds:
1614270080.0
2021-02-25 19:22:17.701154

为什么datetime.now().timestamp()同时返回? time.time()也有同样的问题

我使用 Python 3.8 x32

【问题讨论】:

  • 时间戳“无效”有多远? unix 时间 1614270080.0 在我当地的 UTC+1 时区是 2021-02-25 17:21:20 - 你在 UTC+3 吗?
  • 是的,UTC+3。但相差 3 秒,timestamp() 打印出相同的结果
  • 那么你的问题是时间戳的分辨率太低了?
  • 当我在 repl 中做时间戳时,我得到 1614275190.042707 ...那么小数点后的数字在哪里?不知何故 print(...timestamp()) 没有显示正确的答案。
  • 是的,这很奇怪。该值根本没有变化。

标签: python python-3.x boost-python


【解决方案1】:

timestamp 的类型是float,它是Python 构建宽度的浮点类型。 32 位浮点数不足以表达具有秒精度的时间戳:

>>> import struct
>>> def as_f32(num: float): return struct.unpack('f', struct.pack('f', num))[0]
>>> def as_f64(num: float): return struct.unpack('d', struct.pack('d', num))[0]
>>> # 32-bit expressible timestamps in a 10 second range
>>> set(map(as_f32, range(1614270075, 1614270085)))
{1614270080.0}
>>> # 64-bit expressible timestamps in a 10 second range
>>> set(map(as_f64, range(1614270075, 1614270085)))
{1614270075.0, 1614270076.0, 1614270077.0, 1614270078.0, 1614270079.0, 1614270080.0, 1614270081.0, 1614270082.0, 1614270083.0, 1614270084.0}

如果需要全精度,请使用 64 位版本。

【讨论】:

  • 谢谢!在这上面花了很多时间。
猜你喜欢
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
相关资源
最近更新 更多