Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locale date formatting in Python

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.

like image 430
Alex Avatar asked Jun 12 '09 07:06

Alex


People also ask

How do you format a date in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I format a date in YYYY-MM-DD in Python?

In Python, we can easily format dates and datetime objects with the strftime() function. For example, to format a date as YYYY-MM-DD, pass “%Y-%m-%d” to strftime(). If you want to create a string that is separated by slashes (“/”) instead of dashes (“-“), pass “%Y/%m/%d” to strftime().

What is locale in Python?

Python's locale module is part of the standard library for internationalization (i18n) and localization (l10n) in Python. The locale module allows developers to deal with certain cultural issues in their application. Thereby, they need not know all the specifics of the location or language where the software is used.


1 Answers

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.

like image 115
Piotr Dobrogost Avatar answered Oct 12 '22 01:10

Piotr Dobrogost