3

I am trying to convert the date format '31-Dec-09' to '2009-12-31' in Python with the following code:

df = ['19-Jan-19', '4-Jan-19']   
f = [datetime.datetime.strptime(x,'%d-%mmm-%y').strftime('%Y-%m-%d') for x in df]
print(f)

Getting the following error:

time data '9-Jan-19' does not match format '%d-%mmm-%y'

I have read somewhere that matching a two-digit year '00' would require a lowercase y instead of an upper case one. Either way, I am getting the same error so I guess something else is wrong. Any help?

deceze
  • 510,633
  • 85
  • 743
  • 889
Marvin.Hansen
  • 1,436
  • 1
  • 15
  • 29
  • 3
    Do read the [documentation for `strptime()` carefully](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior), Python `strptime()` doesn't use repeated characters. – Martijn Pieters Jan 24 '19 at 15:54

2 Answers2

15

Your %y and %Y patterns are fine, the issue is that you used %mmm here. The datetime.strptime() method patterns are all single letter patterns, and %mmm is seen as the %m pattern followed by two literal m characters. %m matches a numeric month (1 or 2 digits, zero-padding optional). So 19-1mm-19 would match, but 19-Jan-19 does not because the month is not numeric and the two literal m characters are missing.

The correct pattern to use is '%d-%b-%y' here, where %b matches an abbreviated month name.

Demo:

>>> import datetime
>>> df = ['19-Jan-19', '4-Jan-19']
>>> [datetime.datetime.strptime(x,'%d-%b-%y').strftime('%Y-%m-%d') for x in df]
['2019-01-19', '2019-01-04']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

Since you're specifying month in short hand notation, you should use %b instead of %mmm (That is not a valid format in datetime)

slothdotpy
  • 84
  • 1
  • 3