[Python-ideas] Making datetime __str__ and isoformat more consistent

Skip Montanaro skip at pobox.com
Fri Nov 1 19:15:46 CET 2013


http://bugs.python.org/issue19475

I was told to come here. Is there some reason that datetime objects'
__str__ and isoformat methods shouldn't emit microseconds in all cases
for consistency? As things stand, datetime.strptime() can't reliably
parse what those methods emit. Details on the above (close) ticket.

Here's what I'm talkin' 'bout:

>>> import datetime
>>> dt1 = datetime.datetime(2013, 10, 30, 14, 26, 50)
>>> dt2 = datetime.datetime(2013, 10, 30, 14, 26, 50, 1234)
>>> datetime.datetime.strptime(str(dt1), "%Y-%m-%d %H:%M:%S")
datetime.datetime(2013, 10, 30, 14, 26, 50)
>>> datetime.datetime.strptime(str(dt2), "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/bin/python27/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .001234
>>> datetime.datetime.strptime(str(dt2), "%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2013, 10, 30, 14, 26, 50, 1234)
>>> datetime.datetime.strptime(str(dt1), "%Y-%m-%d %H:%M:%S.%f")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/bin/python27/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '2013-10-30 14:26:50' does not match format
'%Y-%m-%d %H:%M:%S.%f'

Do others agree with me that consistency in this situation is better than
the current behavior?

Thx,

Skip Montanaro


More information about the Python-ideas mailing list