So I\'ve been trying to set the Python locale. I want to because I want to use the weekday name in local language (using strftime(\'%A\')
). But currently the we
It seems like nothing is saved. Am I wrong in assuming you set your locale once and then the system will remember this
yes, calling locale.setlocale()
in Python does not affect future python
processes. Configure environment variables instead, see How to set all locale settings in Ubuntu.
Bash's "date" method seems to pick up the locale some way or the other.
date
calls setlocale(LC_ALL, "")
at the start i.e., you need to call setlocale() at least once per process to enable $LANG locale instead of C locale.
setlocale(LC_ALL, '')
sets locale according to $LANG
variable first, not $LANGUAGE
(it is related but different: "The GNU gettext search path contains 'LC_ALL', 'LC_CTYPE', 'LANG' and 'LANGUAGE', in that order.").
It is enough to set LC_TIME
category (on Ubuntu):
>>> import locale
>>> import time
>>> time.strftime('%A')
'Tuesday'
>>> locale.getlocale(locale.LC_TIME)
('en_US', 'UTF-8')
>>> locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8')
'ru_RU.UTF-8'
>>> time.strftime('%A')
'Вторник'
>>> locale.getlocale(locale.LC_TIME)
('ru_RU', 'UTF-8')
If setlocale()
hasn't raised locale.Error: unsupported locale setting
then the corresponding locale category is set successfully.
You could also get the weekday name knowing its position (in the same python session where the locale is changed):
>>> import calendar
>>> calendar.day_name[1]
'Вторник'
>>> locale.nl_langinfo(locale.DAY_3)
'Вторник'
A portable way, to print a weekday in a given locale without modifying a global state, is to use babel module:
>>> from datetime import date
>>> from babel.dates import format_date # $ pip install babel
>>> format_date(date.today(), format='EEEE', locale='en')
'Tuesday'
>>> format_date(date.today(), format='EEEE', locale='ru')
'вторник'
>>> format_date(date.today(), format='EEEE', locale='nl')
'dinsdag'