How to get localized day-names in django?
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.
You can use different_locale
from calendar
to return a localized day name:
from calendar import day_name, different_locale
def get_localized_day_name(day, locale):
with different_locale(locale):
return day_name[day]
locale
is a string that contains your desired locale, e.g. request.LANGUAGE_CODE
.