Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python does not use locale from environment

Tags:

python

locale

I have a python program (jrnl) that should print the day of the week as text in German. However, it always prints the English name.

Here is the output of locale:

LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC=de_DE.UTF-8
LC_TIME=de_DE.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=de_DE.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=de_DE.UTF-8
LC_NAME=de_DE.UTF-8
LC_ADDRESS=de_DE.UTF-8
LC_TELEPHONE=de_DE.UTF-8
LC_MEASUREMENT=de_DE.UTF-8
LC_IDENTIFICATION=de_DE.UTF-8
LC_ALL=

You can see that LC_TIME is set to de_DE.UTF-8. But when I start python this locale is not set:

>>> import locale
>>> locale.getlocale(locale.LC_TIME)
(None, None)

So my week day is shown in English:

>>> from time import gmtime, strftime
>>> strftime("%A, %d %b %Y %H:%M:%S +0000", gmtime())
'Monday, 15 Jan 2018 20:22:30 +0000'

What do I have to do for python to use the system locale?

like image 731
matthjes Avatar asked Jan 15 '18 20:01

matthjes


1 Answers

From the locale module background documentation:

Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is.

You need to explicitly set the locale using locale.setlocale(); use the empty string to indicate that the user configuration needs to be used:

locale.setlocale(locale.LC_TIME, '')

This is standard behaviour; the underlying C-level locale system explicitly starts in the C locale regardless of environment variables, as you can't assume that the current program actually wants or needs to honour user settings.

like image 124
Martijn Pieters Avatar answered Oct 01 '22 13:10

Martijn Pieters