【发布时间】:2014-08-23 10:31:49
【问题描述】:
我想将具有微秒分辨率的日期时间保存为时间戳。但似乎 Python 3 日期时间模块在加载它们时损失了一微秒。为了测试这一点,让我们创建一个脚本:
test_datetime.py:
from random import randint
from datetime import datetime
now = datetime.now()
for n in range(1000):
d = datetime(year=now.year, month=now.month, day=now.day,
hour=now.hour, minute=now.minute, second=now.second,
microsecond=randint(0,999999))
ts = d.timestamp()
d2 = datetime.fromtimestamp(ts)
assert d == d2, 'failed in pass {}: {} != {}'.format(n, d, d2)
python3 test_datetime.py 总是失败一微秒:
Traceback (most recent call last):
File "test_datetime.py", line 14, in <module>
assert d == d2, 'failed in pass {}: {} != {}'.format(n, d, d2)
AssertionError: failed in pass 4: 2014-07-02 11:51:46.984716 != 2014-07-02 11:51:46.984715
这种行为可以接受吗?如果我们想要微秒级分辨率,我们不应该依赖 datetime.fromtimestamp 吗?
【问题讨论】:
-
使用新微秒值生成新值的稍微简单的方法:
d = now.replace(microsecond=randint(0,999999))。 -
@MartijnPieters:是的,谢谢。我只是想在问题中非常明确。
-
我会找到
now.replace(microsend=randint(0,99999))clearer,因为这样您就不必解析其他 6 个关键字参数来查看您在该行中所做的事情。
标签: python datetime python-3.x unix-timestamp python-3.4