[issue23517] datetime.utcfromtimestamp rounds results incorrectly

Alexander Belopolsky report at bugs.python.org
Sat Sep 5 16:08:38 CEST 2015


Alexander Belopolsky added the comment:

> It doesn't matter who's consuming the rounding of a binary
> float to decimal microseconds

That is true, but what does matter is who is producing the incoming floats.   Consider an extreme case of a timer that ticks twice a microsecond and gives you results in a timespec struct style sec, nsec pair.  If you convert those to timedeltas with timedelta(0, sec, nsec/1000), you will see half of nsec/1000 floats ending in .5 and half ending with .0.  If you have a large sample of (sec, nsec) measurements, the mean of corresponding timedeltas will be 0.25µs larger with the half-up rounding than the actual mean of your samples.

Is round-half-to-even a panacea?  Of course not.  In an extreme case if all your measurements are 1.5µs - it will not help at all, but in a more realistic sample you are likely to have an approximately equal number of even and odd µs and the Dutch rounding will affect the mean much less than round-half-up.

As you said, for most uses none of this matters, but we are not discussing a change to timedelta(0, s) rounding here.  All I want from this issue is to keep the promise that we make in the docs:

On the POSIX compliant platforms, utcfromtimestamp(timestamp) is equivalent to the following expression:

datetime(1970, 1, 1) + timedelta(seconds=timestamp)

https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp

Tim, while we have this entertaining theoretical dispute, I am afraid we are leaving Victor confused about what he has to do in his patch.  I think we agree that fromtimestamp() should use Dutch rounding.  We only disagree why.

If this is the case, please close this thread with a clear advise to use round-half-to-even and we can continue discussing the rationale privately or in a different forum.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23517>
_______________________________________


More information about the Python-bugs-list mailing list