[New-bugs-announce] [issue7342] str(datetime_obj) doesn't include microseconds if their value is 0

Ezio Melotti report at bugs.python.org
Tue Nov 17 23:02:51 CET 2009


New submission from Ezio Melotti <ezio.melotti at gmail.com>:

Last night, test_strptime failed on one of the buildbots [1] with the
following error:
test test_strptime failed -- Traceback (most recent call last):
  File
"C:\buildslave\3.x.moore-windows\build\lib\test\test_strptime.py", line
279, in test_fraction
    tup, frac = _strptime._strptime(str(now), format="%Y-%m-%d %H:%M:%S.%f")
  File "C:\buildslave\3.x.moore-windows\build\lib\_strptime.py", line
332, in _strptime
    (data_string, format))
ValueError: time data '2009-11-16 17:17:14' does not match format
'%Y-%m-%d %H:%M:%S.%f'

The reason is that the __str__ method of datetime objects
(datetime.now() in the test) adds the trailing .%f only if the
microseconds are != 0. Since the possible values of microseconds are
between 0  and 999999 (both included), there is 1 possibility out of
1000000 that the microseconds of datetime.now() are equal to 0 (and
depending on how the value is incremented it might not include 0 among
the possible values at all). Apparently that was the cause of the
failure in the test.

This can be reproduced easily doing:
>>> from datetime import datetime
>>> str(datetime.now())
'2009-11-17 22:11:23.522951'
>>> str(datetime(2012, 12, 21)) # no microseconds
'2012-12-21 00:00:00'

This behavior is defined in Modules/datetimemodule.c, in the C function
datetime_isoformat (line 4145 on py3k, introduced by tim_one in r30151)
and in isoformat_time (line 1278 on trunk, called by datetime_isoformat,
introduced by walter.doerwald in r55714).

Is there a valid reason to omit the microseconds in case they are equal
to 0 instead of just adding the trailing '.000000'?

If the behavior doesn't change the test can be probably fixed checking
the value of the microseconds before the call to str(). The
documentation and other tests to check this should also be added.

(Thanks to R. David Murray for pointing me in the right direction while
I was investigating the problem.)

[1]:
http://www.python.org/dev/buildbot/all/builders/x86%20XP-5%203.x/builds/52/steps/test/logs/stdio

----------
assignee: georg.brandl
components: Documentation, Extension Modules, Tests
messages: 95404
nosy: doerwalter, ezio.melotti, georg.brandl, r.david.murray, tim_one
priority: low
severity: normal
stage: test needed
status: open
title: str(datetime_obj) doesn't include microseconds if their value is 0
type: behavior
versions: Python 2.6, Python 2.7, Python 3.1, Python 3.2

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


More information about the New-bugs-announce mailing list