[Fixed]-Adapt translation method from django to my function

1👍

datetime.strftime() is a method from the Python standard library and doesn’t know anything about your Django language. You can use the builtin date template filter which does respect the Django language.

from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

def date_customerprofile(language):
    now_ = datetime.today()
    if language == 'English':
        translation.activate('en')
        return datefilter(now_, 'l, F j, Y')
    else:
        translation.activate('fr')
        return datefilter(now_, 'l, j F Y')

Seems to give the results you want:

>>> date_customerprofile('English')
u'Thursday, March 30, 2017'
>>> date_customerprofile('French')
u'jeudi, 30 mars 2017'

Some notes:

  • If this is used in the context of one user who has one language, it would be better to set the language on the user’s sessions rather than switch it around just within this function.
  • If you were really serious about localization you would put your custom date formats in format files but it may be overkill for your use case.

Leave a comment