Setting Python locale doesn't work

前端 未结 1 1592
[愿得一人]
[愿得一人] 2020-12-17 23:09

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

相关标签:
1条回答
  • 2020-12-17 23:26

    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'
    
    0 讨论(0)
提交回复
热议问题