'%Y' in strftime() vs. strptime()

Johannes Bauer dfnsonfsduifb at gmx.de
Sun Dec 29 17:02:48 EST 2019


Hi list,

I've just stumbled upon a strange phaenomenon and I'm wondering if it's
a bug. Short and sweet:

Python 3.7.3 (default, Oct  7 2019, 12:56:13)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> from datetime import datetime as d

>>> x = d(1, 1, 1)

>>> x.strftime("%Y-%m-%d")
'1-01-01'

>>> d.strptime(x.strftime("%Y-%m-%d"), "%Y-%m-%d")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data '1-01-01' does not match format '%Y-%m-%d'

>>> d.strptime("0001-01-01", "%Y-%m-%d")
datetime.datetime(1, 1, 1, 0, 0)

I.e. for years that are not 4 digits longs, strftime() produces no
leading zeros for the '%Y' replacement, but strptime() requires leading
zeros.

Is this expected behavior? Shouldn't %Y be consistent across both?

All the best,
Johannes


More information about the Python-list mailing list