If your application is supposed to support more than one locale then getting localized format of date/time by changing locale (by means of locale.setlocale()) is discouraged. For explanation why it's a bad idea see Alex Martelli's answer to the the question Using Python locale or equivalent in web applications? (basically locale is global and affects whole application so changing it might change behavior of other parts of application)

You can do it cleanly using Babel package like this:

>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time

>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'
>>> format_date(d, locale='de_DE')
u'01.04.2007'

See Date and Time section in Babel's documentation.

Answer from Piotr Dobrogost on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › datetime.html
datetime — Basic date and time types
The datetime module has a basic timezone class (for handling arbitrary fixed offsets from UTC) and its timezone.utc attribute (a UTC timezone instance). zoneinfo brings the IANA time zone database (also known as the Olson database) to Python, and its usage is recommended. ... The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and data that represent the history of local time for many representative locations around the globe.
Discussions

python - How do I strftime a date object in a different locale? - Stack Overflow
I have a date object in python and I need to generate a time stamp in the C locale for a legacy system, using the %a (weekday) and %b (month) codes. However I do not wish to change the application's More on stackoverflow.com
🌐 stackoverflow.com
How to change date language?
Hi Plotly Community! I am working with dates and I see all dates are in English format (e.g. Jan 2018), but I would like to configure my layout to use dates in Spanish. I have searched here and in the documentation and I didn’t see something clear about it. More on community.plotly.com
🌐 community.plotly.com
1
0
February 14, 2020
python datetime localization - Stack Overflow
without having to change my whole operating system's locale (i.e. just use python calls to dynamically set the locale and keep the changes scoped within my app) More on stackoverflow.com
🌐 stackoverflow.com
Format language date_format '%B' in python
Get notified when there's activity on this post · I'm modifing a module to get the full month (translated) instead of Y/m/d: More on odoo.com
🌐 odoo.com
1
1
March 2, 2017
🌐
Lokalise
lokalise.com › home › date and time localization with formats | lokalise
Date and time localization with formats | Lokalise
2 weeks ago - In this article, we’ve explored how to handle date and time localization across several popular programming languages, including Python, PHP, Java, JavaScript, and Ruby on Rails. We’ve covered essential tools and methods like DateTime, Intl.DateTimeFormat, ZonedDateTime, and Rails’ localize ...
🌐
Skybert
skybert.net › python › formatting-python-dates-according-to-locale
Formatting Python Dates According to Locale | skybert.net
As long as you've set the locale, using the locale.setlocale() method, any calls to datetime.strftime() produce output according to the locale set. ... ~ /home ⌂ ~ talks 💬 ~ aifail ~ bash ~ book ~ craftsmanship ~ db ~ dongxi ~ emacs ~ escenic ~ essays ~ games ~ hardware ~ iam ~ java ~ js ~ language ~ latex ~ ldap ~ life ~ linux ~ mac-os-x ~ misc ~ mt-foo ~ network ~ norsk ~ python ~ quotes ~ running ~ security ~ travel ~ unix ~ various ~ vcs ~ webdesign ~ windows ~ discoveries ~ cv 🧙 ~
🌐
Python
bugs.python.org › issue29457
Issue 29457: strftime('%x') does not use my locale - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/73643
🌐
Python
docs.python.org › 3 › library › locale.html
locale — Internationalization services
Source code: Lib/locale.py The locale module opens access to the POSIX locale database and functionality. The POSIX locale mechanism allows programmers to deal with certain cultural issues in an ap...
🌐
WordPress
mike632t.wordpress.com › 2018 › 04 › 08 › dates-and-locale-settings-in-python
Dates and Locale settings in Python | Notes on Linux
April 8, 2018 - >>> locale.setlocale(locale.LC_TIME, 'de_DE.ISO8859-1') 'de_DE.ISO8859-1' >>> datetime.datetime.today().strftime('%x') '16.01.2018' >>> datetime.datetime.today().strftime('%c') 'Di 16 Jan 2018 16:24:28 ' If support for the specified locale is not available then you will get an error. >>> locale.setlocale(locale.LC_TIME, 'en_US.UTF-8') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/locale.py", line 579, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting >>>
Top answer
1 of 3
55

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.

2 of 3
21

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/python3
import time
import locale


def 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 french
locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')

# Should print french, english, then french
print(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/python3
import time
import locale
import contextlib

@contextlib.contextmanager
def 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 french
locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')

# Should print french, english, then french
print(time.strftime('%a-%b'))
print(get_c_locale_abbrev())
print(time.strftime('%a-%b'))
Find elsewhere
🌐
Phrase
phrase.com › home › resources › blog › a beginner’s guide to python’s locale module
A Beginner's Guide to Python's locale Module | Phrase
September 25, 2022 - Other than that, the datetime module helps in formatting date and time, based on the locale that you have set. The easiest way is to rely on the strftime() function. It converts an object to a string according to a given format.
🌐
Absolutecodeworks
absolutecodeworks.com › python-display-date-and-time-in-local-language
Display date and time in local language in Python - Absolute Code Works
August 29, 2022 - To display a specified date in local language and format, we have to use the python library locale. Identify the correct locale code for each country and use it directly as below.
🌐
Pocoo
babel.pocoo.org › en › latest › dates.html
Date and Time — Babel 2.17.0 documentation
>>> format_date(d, format='short', locale='en') '4/1/07' >>> format_date(d, format='long', locale='en') 'April 1, 2007' >>> format_date(d, format='full', locale='en') 'Sunday, April 1, 2007' Working with dates and time can be a complicated thing. Babel attempts to simplify working with them by making some decisions for you. Python’s datetime module has different ways to deal with times and dates: naive and timezone-aware datetime objects.
Top answer
1 of 7
90

As of python 3.6 calling astimezone() without a timezone object defaults to the local zone (docs). This means you don't need to import tzlocal and can simply do the following:

#!/usr/bin/env python3

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc)

print("Local time {}".format(utc_dt.astimezone().isoformat()))

This script demonstrates a few other ways to show the local timezone using astimezone():

#!/usr/bin/env python3

import pytz
from datetime import datetime, timezone
from tzlocal import get_localzone

utc_dt = datetime.now(timezone.utc)

PST = pytz.timezone("US/Pacific")
EST = pytz.timezone("US/Eastern")
JST = pytz.timezone("Asia/Tokyo")
NZST = pytz.timezone("Pacific/Auckland")

print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Eastern time {}".format(utc_dt.astimezone(EST).isoformat()))
print("UTC time     {}".format(utc_dt.isoformat()))
print("Japan time   {}".format(utc_dt.astimezone(JST).isoformat()))

# Use astimezone() without an argument
print("Local time   {}".format(utc_dt.astimezone().isoformat()))

# Use tzlocal get_localzone
print("Local time   {}".format(utc_dt.astimezone(get_localzone()).isoformat()))

# Explicitly create a pytz timezone object
# Substitute a pytz.timezone object for your timezone
print("Local time   {}".format(utc_dt.astimezone(NZST).isoformat()))

It outputs the following:

$ ./timezones.py 
Pacific time 2019-02-22T17:54:14.957299-08:00
Eastern time 2019-02-22T20:54:14.957299-05:00
UTC time     2019-02-23T01:54:14.957299+00:00
Japan time   2019-02-23T10:54:14.957299+09:00
Local time   2019-02-23T14:54:14.957299+13:00
Local time   2019-02-23T14:54:14.957299+13:00
Local time   2019-02-23T14:54:14.957299+13:00
2 of 7
40

Think your should look around: datetime.astimezone()

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

Also see pytz module - it's quite easy to use -- as example:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

Example:

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00
🌐
Statology
statology.org › home › how to localize dates to specific time zones in python
How to Localize Dates to Specific Time Zones in Python
August 15, 2024 - pytz library: A third-party library that provides time zone definitions for Python. To create a time zone aware datetime object, you can use the localize() method from pytz:
🌐
sqlpey
sqlpey.com › python › top-2-methods-for-locale-based-date-formatting-in-python
Top 2 Methods for Locale-Based Date Formatting in Python - …
November 23, 2024 - If your application needs to cater to multiple languages, using the Babel library is an excellent way to achieve localized date and time formatting without affecting global locale settings. This approach prevents unintended changes in other parts of your application. ... from datetime import date from babel.dates import format_date ## Create a date object d = date(2007, 4, 1) ## Format the date in English english_format = format_date(d, locale='en') print(english_format) # Output: 'Apr 1, 2007' ## Format the same date in German german_format = format_date(d, locale='de_DE') print(german_format) # Output: '01.04.2007'
🌐
Real Python
realpython.com › ref › stdlib › locale
locale | Python Standard Library – Real Python
The Python locale module provides tools to handle the localization of programs, such as formatting numbers, dates, and currencies according to the conventions of different locales.
🌐
Squash
squash.io › complete-guide-how-to-use-python-locale
How to Use Python with Multiple Languages (Locale Guide)
November 23, 2023 - By combining the capabilities of the locale module with time zone conversion libraries, you can handle localization and time zone-related tasks effectively. import datetime import pytz # Set the timezone to UTC timezone_utc = pytz.timezone('UTC') ...