Locale troubles

2019-08-05 06:59发布

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32.

>>> 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

So... Why doesn't it work without resetting the default locale? Is it OS related? Is there a way to do something like locale.setlocale(convert_it_somehow(locale.getdefaultlocale()))? All I want to do is to display dates according to user's preference. Thanks!

标签: python locale
1条回答
趁早两清
2楼-- · 2019-08-05 07:45

The thing to realize about locales is that Python, as a programming language implementation rather than an application, can't assume whether the environments locale setting (through the LANG and LC_* environment variables) should be applied to a program written in Python or not. So, Python does not set the locale. Your program has to do so explicitly. Python does parse the locale variables for you, and that's what locale.getdefaultlocale() returns: the default locale as specified by the environment.

The active locale, the one actually used, is returned by locale.getlocale(), and if you run that before explicitly setting the locale you will see it returns (None, None) (to indicate that no locale is set.) If you want your application to use the default locale specified by the environment, you have to call locale.setlocale(locale.LC_ALL, ''). (The empty string means "whatever is the default", and is unfortunately different from None or not passing the argument.)

查看更多
登录 后发表回答