Search code examples
pythondatetimeunicodelocale

UnicodeEncodeError when parsing month name with Python strptime


I have to parse a German date in MONTH YEAR format where MONTH is the full name of the month. I set the appropriate locale in Python and then try to parse the date with strptime. For example:

locale.setlocale(locale.LC_ALL, "deu_deu") # Locale name on Windows
datetime.strptime(dt, "%B %Y")

On encountering a month with a non-ASCII character in its name I get a UnicodeEncodeError. The date is being pulled from an XML file delivered via a web service. Is there a way I can transform my date string to that it works with strptime?


Solution

  • The following code solves the problem.

    locale.setlocale(locale.LC_ALL, "deu_deu") # Locale name on Windows
    datetime.strptime(dt.encode("iso-8859-16"), "%B %Y")