Date/Time Localization in Django (python-side)

(0 comments)

There are two sides in localization in Django framework: Templates and Python-side.

There are a lot of good stuff about template side in Django Documentation, how ever what if you need to get time using datetime module?

Lets go over date.today using "%B %Y" format:

>>> from datetime import date
>>> today = date.today()
>>> print(today.strftime("%B %Y"))
March 2017

What if I need this for subject of an e-mail or sms message that will be sent from django app?

Let's assume that we have user object, and it has CharField language with value 'ru'. First of all, we will need to activate language:

>>> from django.utils.translation import activate
>>> activate(user.language)

Our e-mail subject will be "Topics for March 2017" and in Russian "Темы для Март 2017":

>>> from django.utils.translation import ugettext_lazy as _
>>> subject = _("Topics for {date}").format(date=today.strftime("%B %Y"))
>>> print(subject)
Темы для March 2017

As you can see, month stays in English. In that case one possible solution can be to parse month name ("March"), use it's translation and add only year from today.year:

>>> month_name = _(today.strftime("%B"))
>>> subject = _("Topics for {month}, {year}").format(month=month_name, year=today.year)
>>> print(subject)
Темы для Март, 2017

Another way is to use django.utils.formats function:

>>> from django.utils import formats
>>> date = formats.date_format(today, format="YEAR_MONTH_FORMAT", use_l10n=True)
>>> subject = _("Topics for {date}").format(date=date)
>>> print(subject)
Темы для Март 2017 г.

If you have USE_L10N = True in settings, no need for use_l10n attribute.

Second way is more practical and first gives you better control for localization (like adding extra words for different locales).

You can find here all allowed date format strings.

Hope it helped you and if you have a better idea to solve that problem, please, write them in comments.

Current rating: 4

Comments

There are currently no comments

New Comment

required

required (not published)

optional