0

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?

AJMansfield
  • 4,039
  • 3
  • 29
  • 50
Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253
  • 3
    Capital `Y` for a 4 digit year - eg: `%Y-%m-%d`. What exactly are you trying to achieve anyway? It's odd to take the str rep of a date only to convert it to a datetime, then take the date back... – Jon Clements Mar 09 '14 at 15:37
  • @JonClements it should be ab answer. what does small means? – Grijesh Chauhan Mar 09 '14 at 15:38
  • @GrijeshChauhan lower case `y` is 2 digit year... See [this site](http://strftime.org/) for info... Or the [official docs](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) – Jon Clements Mar 09 '14 at 15:40
  • @JonClements thanks, its almost same as I have been [used in C](http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=/rtref/strpti.htm) also – Grijesh Chauhan Mar 09 '14 at 15:44
  • 1
    @GrijeshChauhan it's based on the C library :) – Jon Clements Mar 09 '14 at 15:46

2 Answers2

4

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.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
3

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.

dawg
  • 98,345
  • 23
  • 131
  • 206