Locale date formatting in Python

Viewed 124607

How do I get datetime.datetime.now() printed out in the native language?

>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'

I'd like to get the same result but in local language.

6 Answers

You can just set the locale like in this example:

>>> import time
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
Sun, 23 Oct 2005 20:38:56
>>> import locale
>>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
'sv_SE'
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
sön, 23 okt 2005 20:39:15

solution for russian language and cross platform

import sys
import locale
import datetime

if sys.platform == 'win32':
    locale.setlocale(locale.LC_ALL, 'rus_rus')
else:
    locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

print(datetime.date.today().strftime("%B %Y"))

Ноябрь 2017

This solution works in current Python 3.9 but also in Python 2.7. There is no need to mess around with local. Just use the strftime() format strings %c (date and time), %x (date only) or %X (time only):

>>> from datetime import datetime
>>> now = datetime.now()
>>> now.strftime('%c')
'So 29 Mai 2022 17:06:17 '
>>> now.strftime('%x')
'29.05.2022'
>>> now.strftime('%X')
'17:06:17'
Related