Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get localized day-names in django?

When using djangos (or better gettext's) localization mechanism, it's hard to get the current locale's day names. Usually, i would use calendar:

calendar.day_name[current_day]

Where current_day is a int between 0 and 6. This won't work, as Django does not seem to set the requested locale correctly. Same situation for month names.

So, how to localize calendar-names correctly?

like image 795
michi.0x5d Avatar asked Jun 25 '16 15:06

michi.0x5d


1 Answers

You can use django.utils.formats.date_format.

>>> from django.utils.formats import date_format
>>> from django.utils import translation
>>> from datetime import date
>>> date_format(date.today(), 'l')
'Saturday'
>>> translation.activate('fr')
>>> date_format(date.today(), 'l')
'samedi'

translation.activate is useless in the context of a request where translation is already activated. I used it here for example purpose.

If you don't have a specific date and need the name of a day of the week, just use gettext to translate it:

>>> import calendar
>>> from django.utils import translation
>>> from django.utils.translation import gettext as _
>>> translation.activate('fr')
>>> _(calendar.day_name[0])
'lundi'

Note that the reason why _(day_name) works, although "day_name" is a variable, is because day names are already translated by Django, and thus don't need to be discovered by gettext.

like image 84
Antoine Pinsard Avatar answered Oct 07 '22 02:10

Antoine Pinsard