[issue19475] Add microsecond flag to datetime isoformat()

Marc-Andre Lemburg report at bugs.python.org
Wed Nov 6 18:05:25 CET 2013


Marc-Andre Lemburg added the comment:

On 06.11.2013 16:51, Alexander Belopolsky wrote:
> 
> MAL: Have you thought about the rounding/truncation issues
> associated with not showing microseconds ?

Sure, otherwise I wouldn't have mentioned it :-)

mxDateTime always uses 2 digit fractions when displaying date/time values.
This has turned out to be a good compromise between accuracy and
usability. In early version, I used truncation, but that caused
(too many) roundtrip problems, so I started using careful rounding
in later versions:

/* Fix a second value for display as string.

   Seconds are rounded to the nearest microsecond in order to avoid
   cases where e.g. 3.42 gets displayed as 03.41 or 3.425 is diplayed
   as 03.42.

   Special care is taken for second values which would cause rounding
   to 60.00 -- these values are truncated to 59.99 to avoid the value
   of 60.00 due to rounding to show up even when the indicated time
   does not point to a leap second. The same is applied for rounding
   towards 61.00 (leap seconds).

   The second value returned by this function should be formatted
   using '%05.2f' (which rounds to 2 decimal places).

*/

This approach has worked out well, though YMMV.

> I believe it has to be the truncation.  Rounding is better left to the user code where it can be done either using timedelta arithmetics or at the time source.  I would expect that in the majority of cases where lower resolution printing is desired the times will be already at lower resolution at the source.

In practice you often don't know the resolution of
the timing source. Nowadays, the reverse of what you said
is usually true: the source resolution is higher than the
precision you use to print it.

MS SQL Server datetime is the exception to that rule, with a
resolution of 333ms and weird input "rounding":

http://msdn.microsoft.com/en-us/library/ms187819.aspx

For full seconds, truncation will add an error of +/- 1 second,
whereas rounding only adds +/- 0.5 seconds. This is what convinced
me to use rounding instead of truncation.

----------

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


More information about the Python-bugs-list mailing list