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.
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.
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().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With