In accordance with the documentation , strftime () should return localized date and time values ​​(name of months and days of the week, etc.), however, it does this only after explicitly setting the locale:

>>> locale.getlocale() # Проверим текущую локаль ('ru_RU', 'UTF-8') >>> d1.strftime('%A') 'Sunday' >>> locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') 'ru_RU.UTF-8' >>> locale.getlocale() ('ru_RU', 'UTF-8') >>> d1.strftime('%A') 'Воскресенье' 

Why does it start to print in Russian only after redefining the locale, although before that it was ('ru_RU', 'UTF-8') ? Moreover, it is rather simple to make resetlocale:

 >>> import locale >>> locale.getdefaultlocale() ('ru_RU', 'UTF-8') >>> locale.getlocale() ('ru_RU', 'UTF-8') >>> d1.strftime('%A') 'Sunday' >>> locale.resetlocale() >>> d1.strftime('%A') 'Воскресенье' 

    1 answer 1

    All programs on * nix systems (not only python ) start using the C (POSIX) locale until they call setlocale(LC_ALL, '') to activate a custom locale.

    If you do not want locale to activate for the process, then you can use libraries that explicitly allow the language to choose, such as PyICU ( use case ) —is easier libraries that can work for a specific task, for example humanize :

     >>> import datetime >>> import humanize # $ pip install humanize >>> _ = humanize.i18n.activate('ru_RU') >>> humanize.naturaltime(datetime.datetime.now()) 'сейчас' 

    Q: but why does locale.getlocale() ru_RU ?

    I would also expect something like (None, None) instead of ('ru_RU', 'UTF-8') before setlocale(LC_ALL, '') called in the program. From the documentation: "Returns the current setting for the given locale category" it is not obvious that user settings from environment variables ( LC_* , LANG ) are read, and not the current default locale ( "The POSIX locale is the default global locale at entry to main() " ) is returned before calling setlocale(LC_ALL, '') .

    locale module is a thin wrapper around the corresponding C functionality, in particular, the behavior may depend on the platform. The current implementation of locale.getlocale() equivalent to C setlocale(category, NULL) , which queries the current setting for the locale ( "query the current global locale setting" ).

    Why "the current global locale setting" is not equal to the "default global locale" before calling setlocale(LC_ALL, '') I do not understand. Maybe it's in the word setting vs. locale , that is, the current setting before calling setlocale(LC_ALL, '') is taken from the environment variables ( LC_* , etc), and the current locale before calling setlocale(LC_ALL, '') , used by strftime() , is C (as expected ). But this is pure speculation on my part.

    • OK, but why does locale.getlocale () produce ru_RU? - aryndin
    • @ jumpjet67: tried to reply to a comment, but briefly: I do not know. - jfs