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

DDD
Release: 2024-10-25 06:02:29
Original
1001 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template