[New-bugs-announce] [issue44831] Inconsistency between datetime.now() and datetime.fromtimestamp(time.time(), None)

Miksus report at bugs.python.org
Wed Aug 4 13:49:51 EDT 2021


New submission from Miksus <koli.mikael at gmail.com>:

I am trying to measure time twice and the second measurement gives a time that is 1 microsecond before the first measurement about half of the time.

My experiment in short:
---------------------------------------------------
import time, datetime
start = time.time()
end = datetime.datetime.now()

start = datetime.datetime.fromtimestamp(start, None)
assert end >= start # fails about half the time.
---------------------------------------------------


The problem is somewhat interesting. This does not fail:
---------------------------------------------------
import time, datetime
start = time.time()
end = time.time()

start = datetime.datetime.fromtimestamp(start, None)
end = datetime.datetime.fromtimestamp(end, None)
assert end >= start
---------------------------------------------------

And neither does this:
---------------------------------------------------
import datetime
start = datetime.datetime.now()
end = datetime.datetime.now()
assert end >= start
---------------------------------------------------

And it seems datetime.datetime.now() works the same way as to how I handled the "start" time in my first experiment: 
https://github.com/python/cpython/blob/3.6/Lib/datetime.py#L1514
and therefore the issue seems to be under the hood.

I have tested this on two Windows 10 machines (Python 3.6 & 3.8) in which cases this occurred. This did not happen on Raspberry Pi OS using Python 3.7.

In short:
- The time module imported in datetime.datetime.now() seems to measure time slightly differently than the time module imported by a Python user.
- This seems to be Windows specific.

My actual application has some code in between the measurements suffering from the same problem thus this is not an issue affecting only toy examples.

----------
components: Library (Lib), Windows
messages: 398919
nosy: Miksus, paul.moore, steve.dower, tim.golden, zach.ware
priority: normal
severity: normal
status: open
title: Inconsistency between datetime.now() and datetime.fromtimestamp(time.time(), None)
versions: Python 3.6, Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44831>
_______________________________________


More information about the New-bugs-announce mailing list