Home  >  Article  >  Backend Development  >  How to Format Dates and Times in Python for Different Locales?

How to Format Dates and Times in Python for Different Locales?

DDD
DDDOriginal
2024-10-25 06:02:29935browse

How to Format Dates and Times in Python for Different Locales?

Locale Date Formatting in Python

In Python, the native language is not used by default for formatting dates and times retrieved from datetime.datetime.now(). This may lead to unexpected string representations, as seen in the example:

<code class="py">>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'</code>

To obtain the localized format, using the locale module by setting its default value is not recommended. This approach could alter the behavior of other parts of the application since locale affects the entire program.

A cleaner solution involves using the Babel package. With Babel, you can easily format dates and times according to the desired locale:

<code class="py">>>> 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'</code>

Refer to the Date and Time section of Babel's documentation for additional information on this functionality. By leveraging Babel, you can ensure that dates and times are formatted appropriately for the user's local environment.

The above is the detailed content of How to Format Dates and Times in Python for Different Locales?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn