System date formatting not using django locale

Pierre de LESPINAY picture Pierre de LESPINAY · May 29, 2012 · Viewed 10.6k times · Source

Trying to understand L10N implementation into Django, Here are my settings

LANGUAGE_CODE = 'fr-FR'
USE_L10N = True

If I try

>>> datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M')
      .strftime('%c')

It will give me 'Wed May 30 15:30:00 2012' that is the EN locale. However the doc is saying:

[...] Two users accessing the same content, but in different language, will see date and number fields formatted in different ways, depending on the format for their current locale [...]

Are they talking about the locale set for their respective browser ?
If not, how can I set it to french by default for example ?

Answer

Karmel picture Karmel · May 29, 2012

Django's localization works in the context of Django templates and forms, and can not travel up the chain to Python's internal datetime representations:

When using Django's formatting system, dates and numbers on templates 
will be displayed using the format specified for the current locale. 
...Django will also use localized formats when parsing data in forms. 

So if you have USE_L10N = True and a user with the region FR enters 10,45 into a form, that will be interpreted to mean 10.45 in the English decimal system. Similarly, the output of a template tag like {{ value|date:"SHORT_DATE_FORMAT" }} will vary based on the user's locale.

However, the Python internal strftime('%c') doesn't access Django's settings, and instead refers to the locale set on the machine on which it is installed. You can retrieve and change the locale settings Python points to with:

>>> datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M').strftime('%c')
'Wed May 30 15:30:00 2012'
>>> import locale
>>> locale.getlocale()
(None, None)
>>> locale.getdefaultlocale()
('en_US', 'UTF-8')
>>> locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
'fr_FR.UTF-8'
>>> datetime.datetime.strptime('2012-05-30 15:30', '%Y-%m-%d %H:%M').strftime('%c')
'Mer 30 mai 15:30:00 2012'

Or by setting the environment variable $LANG.