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 locale
import threading

from datetime import datetime
from contextlib import contextmanager


LOCALE_LOCK = threading.Lock()

@contextmanager
def 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 locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')

# Example to write a formatted English date
with setlocale('C'):
    print(datetime.now().strftime('%a, %b')) # e.g. => "Thu, Jun"

# Example to read a formatted English date
with 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.

Leave a Comment