以下Python代码适用于我的Windows机器(Python 2.5.4),但不适用于我的Debian机器(Python 2.5.0).我猜这是依赖操作系统的.
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/locale.py", line 476, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
Run Code Online (Sandbox Code Playgroud)
问题:
我的日期格式为德语,例如,
2. Okt. 2009
Run Code Online (Sandbox Code Playgroud)
也许也是
2. Oct. 2009
Run Code Online (Sandbox Code Playgroud)
如何将其解析为ISO datetime(或python datetime)?
通过使用此代码段解决:
for l in locale.locale_alias:
worked = False
try:
locale.setlocale(locale.LC_TIME, l)
worked = True
except:
worked = False
if worked: print l
Run Code Online (Sandbox Code Playgroud)
然后在setlocale中插入适当的参数l.
可以解析使用
import datetime
print datetime.datetime.strptime("09. Okt. 2009", "%d. %b. %Y")
Run Code Online (Sandbox Code Playgroud) 我想获得一个unicode版本calendar.month_abbr[6].如果我没有为语言环境指定编码,我不知道如何将字符串转换为unicode.下面的示例代码显示了我的问题:
>>> import locale
>>> import calendar
>>> locale.setlocale(locale.LC_ALL, ("ru_RU"))
'ru_RU'
>>> print repr(calendar.month_abbr[6])
'\xb8\xee\xdd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 0: unexpected code byte
>>> locale.setlocale(locale.LC_ALL, ("ru_RU", "utf8"))
'ru_RU.UTF8'
>>> print repr(calendar.month_abbr[6])
'\xd0\x98\xd1\x8e\xd0\xbd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
u'\u0418\u044e\u043d'
Run Code Online (Sandbox Code Playgroud)
任何想法如何解决这个问题?解决方案不必看起来像这样.任何给我在unicode中缩写月份名称的解决方案都很好.
win32上的Python 2.7.2(默认,2011年6月12日,14:24:46)[MSC v.1500 64位(AMD64)].
>>> locale.getdefaultlocale()
('ru_RU', 'cp1251') #ok, Russian locale is set, as per user settings
>>> a = datetime.date.today()
>>> a.strftime("%B %d")
March 22' #ouch, that's not Russian.
>>> locale.setlocale(locale.LC_ALL, 'russian_russia')
'Russian_Russia.1251'
>>> a.strftime("%B %d")
'???? 22' #now it's ok
Run Code Online (Sandbox Code Playgroud)
那么......为什么不重置默认语言环境不行呢?它与操作系统有关吗?有办法做某事locale.setlocale(convert_it_somehow(locale.getdefaultlocale()))吗?我想要做的就是根据用户的偏好显示日期.谢谢!