I want to save datetimes with microsecond resolution as timestamps. But it looks like the Python 3 datetime module lost one microsecond at boot time. To test this, create a script:
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 always crash for one microsecond:
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
Can this behavior be accepted? Should we not rely on datetime.fromtimestamp if we want to get resolution in microseconds?
source
share