3

Need to change a string in German into a date. I try to use the following code:

from datetime import datetime
datetime_object = datetime.strptime('24. Juli 2017', '%d %B %Y')
print(datetime.strftime(datetime_object, '%d.%m.%Y'))

this code fails with the next error:

ValueError: time data '24. Juli 2017' does not match format '%d %B %Y'

However it works correct with English text:

datetime_object = datetime.strptime('24 July 2017', '%d %B %Y')
print(datetime.strftime(datetime_object, '%d.%m.%Y'))

Output:

24.07.2017
Roman
  • 1,883
  • 2
  • 14
  • 26
  • 1
    This question may be helpful: https://stackoverflow.com/questions/28429512/python-parsing-date-and-find-the-correct-locale-setting. On sumarry you first have to cahnge the locale to Germany and then it will parse months in german – Carlos Gonzalez Mar 21 '19 at 10:10
  • 2
    I found simple way, using "dateparser" lib. `import dateparser print(dateparser.parse('24. Juli 2017').strftime('%d.%m.%Y'))` works perfect – Roman Mar 21 '19 at 12:51

1 Answers1

3

You have to fix the format (forget the dot after day) and have to set locale to 'de_DE'.

>>> from datetime import datetime
>>> import locale
>>> locale.setlocale(locale.LC_TIME, "de_DE") # german
'de_DE'
>>> datetime.strptime('24. Juli 2017', '%d. %B %Y')
datetime.datetime(2017, 7, 24, 0, 0)