Question

I am trying to parse dates in the ISO date format, but for reasons I don't understand, the pattern I am using isn't working.

From the shell:

>>> s
datetime.date(2014, 1, 3)
>>> str(s)
'2014-01-03'
>>> datetine.strptime(str(s),"%y-%m-%d").date()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python27\lib\_strptime.py", line 325, in _strptime
    (date_string, format))
ValueError: time data '2014-01-30' does not match format '%y-%m-$d'

But 2014-01-03 should be a match to %y-%m-%d, right? Why am I getting this error?

Was it helpful?

Solution

From the docs (emphasis mine):

%y Year without century as a zero-padded decimal number. 00, 01, ..., 99
%Y Year with century as a decimal number. 1970, 1988, 2001, 2013

Therefore %y-%m-%d is expecting 14-01-03 while you have 2014-01-03 which requires %Y-%m-%d.

OTHER TIPS

Difference between upper and lower case:

>>> datetime.datetime.strptime('2014-01-03', '%Y-%m-%d').date()
datetime.date(2014, 1, 3)
>>> datetime.datetime.strptime('14-01-03', '%y-%m-%d').date()
datetime.date(2014, 1, 3)

Documented in strptime and strftime behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top