使用Python strptime解析月份名称时的UnicodeEncodeError [英] UnicodeEncodeError when parsing month name with Python strptime

查看:156
本文介绍了使用Python strptime解析月份名称时的UnicodeEncodeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在MONTH YEAR格式中解析德语日期,其中MONTH是该月的全名。我在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")

遇到一个非ASCII字符的月份在其名称中,我得到一个 UnicodeEncodeError 。日期是从通过Web服务传递的XML文件中提取的。有没有办法可以将日期字符串转换成与 strptime 一起使用的日期字符串?

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?

编辑

datetime.strptime(dt.encode("iso-8859-16"), "%B %Y") 

work。

推荐答案

以下代码解决了问题。

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

这篇关于使用Python strptime解析月份名称时的UnicodeEncodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆