How do I strftime a date object in a different locale? [duplicate] How do I strftime a date object in a different locale? [duplicate] python python

How do I strftime a date object in a different locale? [duplicate]


The example given by Rob is great, but isn't threadsafe. Here's a version that works with threads:

import localeimport threadingfrom datetime import datetimefrom contextlib import contextmanagerLOCALE_LOCK = threading.Lock()@contextmanagerdef setlocale(name):    with LOCALE_LOCK:        saved = locale.setlocale(locale.LC_ALL)        try:            yield locale.setlocale(locale.LC_ALL, name)        finally:            locale.setlocale(locale.LC_ALL, saved)# Let's set a non-US localelocale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')# Example to write a formatted English datewith setlocale('C'):    print(datetime.now().strftime('%a, %b')) # e.g. => "Thu, Jun"# Example to read a formatted English datewith setlocale('C'):    mydate = datetime.strptime('Thu, Jun', '%a, %b')

It creates a threadsafe context manager using a global lock and allows you to have multiple threads running locale-dependent code by using the LOCALE_LOCK. It also handles exceptions from the yield statement to ensure the original locale is always restored.


No, there is no way to call strftime() with a specific locale.

Assuming that your app is not multi-threaded, save and restore the existing locale, and set your locale to 'C' when you invoke strftime.

#! /usr/bin/python3import timeimport localedef get_c_locale_abbrev():  lc = locale.setlocale(locale.LC_TIME)  try:    locale.setlocale(locale.LC_TIME, "C")    return time.strftime("%a-%b")  finally:    locale.setlocale(locale.LC_TIME, lc)# Let's suppose that we're frenchlocale.setlocale(locale.LC_ALL, 'fr_FR.utf8')# Should print french, english, then frenchprint(time.strftime('%a-%b'))print(get_c_locale_abbrev())print(time.strftime('%a-%b'))

If you prefer with: to try:-finally:, you could whip up a context manager:

#! /usr/bin/python3import timeimport localeimport contextlib@contextlib.contextmanagerdef setlocale(*args, **kw):  saved = locale.setlocale(locale.LC_ALL)  yield locale.setlocale(*args, **kw)  locale.setlocale(locale.LC_ALL, saved)def get_c_locale_abbrev():  with setlocale(locale.LC_TIME, "C"):    return time.strftime("%a-%b")# Let's suppose that we're frenchlocale.setlocale(locale.LC_ALL, 'fr_FR.utf8')# Should print french, english, then frenchprint(time.strftime('%a-%b'))print(get_c_locale_abbrev())print(time.strftime('%a-%b'))


take a look to the pytz package

you can use like this

import pytzUTC = pytz.timezone('UTC') # utcfr = pytz.timezone('Europe/Paris') #your localfrom datetime import datetimedate = datetime.now(fr)dateUTC = date.astimezone(UTC)

strftime will render in the timezone specified

for have month name in the locale use calendar for example :

import calendarprint calendar.month_name[dateUTC.month] #will print in the locale

inspect more deeply calendar for having more information