2

I have this string

14 Mai 2014

I want to convert it to iso 8601

i read this answer and this one,

and first i try to convert string to date and then in i convert it to iso format:

test_date = datetime.strptime("14 Mai 2014", '%d %m %Y')
iso_date = test_date.isoformat()

i got this error:

ValueError: time data '14 Mai 2014' does not match format '%d %m %Y'
Community
  • 1
  • 1
parik
  • 2,313
  • 12
  • 39
  • 67

2 Answers2

5

According to Python strftime reference %m means day of month and in your case "Mai" seems to be name of month in your current locale and you have to use this %b format. So your piece of code should looks like this:

test_date = datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()

And don't forget to set locale.

For English locale it works:

>>> from datetime import datetime
>>> test_date = datetime.strptime("14 May 2014", '%d %b %Y')
>>> print(test_date.isoformat())
2014-05-14T00:00:00
dikkini
  • 1,184
  • 1
  • 23
  • 52
2

You need to use %b token instead of %m.
And for use %b token you must set a locale.
Python Documentation

import datetime
import locale

locale.setlocale(locale.LC_ALL, 'fr_FR')
test_date = datetime.datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()

The result will be '2014-05-14T00:00:00'

Simasim
  • 66
  • 7