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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With