Python: date formatted with %x (locale) is not as

2019-04-11 00:58发布

I have a datetime object, for which I want to create a date string according to the OS locale settings (as specified e.g. in Windows'7 region and language settings).

Following Python's datetime formatting documentation, I used the %x format code which is supposed to output "Locale’s appropriate date representation.". I expect this "representation" to be either Windows "short date" or "Long date" format, but it isn't either one. (I have the short date format set to d/MM/yyyy and the long date format to dddd d MMMM yyyy, but the output is dd/MM/yy)

What's wrong here: the Python documentation, the Python implementation, or my expectation ? (and how to fix?)

2条回答
家丑人穷心不美
2楼-- · 2019-04-11 01:50

Is your locale set in your script? If you call locale.getlocale(), is the result expected? Compare below:

>>> import locale
>>> locale.getlocale()
(None, None)
>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2010, 8, 9)
>>> today.strftime('%x')
'08/09/10'
>>> locale.setlocale(locale.LC_ALL, "de_DE.UTF-8")
'de_DE.UTF-8'
>>> locale.getlocale()
('de_DE', 'UTF8')
>>> today.strftime('%x')
'09.08.2010'

Note that there are bugs in the datetime module, mostly because of bugs in the underlying C libraries. On my installation (latest OS X), for example, the formatting string %z is completely unavailable.

On Windows, the syntax of locale strings available to setlocale() follows a different syntax than on *nix platforms. A list is here on MSDN.

And if you just wish to set your script to whatever default locale your users have installed (in mine: UK English), you just do this at the beginning of the main script. Don't do it in modules, as it overrides a global variable:

>>> locale.setlocale(locale.LC_ALL, "")
'en_GB.UTF-8'
查看更多
Ridiculous、
3楼-- · 2019-04-11 02:04

After reading the setlocale() documentation, I understood that the default OS locale is not used by Python as the default locale. To use it, I had to start my module with:

import locale
locale.setlocale(locale.LC_ALL, '')

Alternatively, if you intend to only reset the locale's time settings, use just LC_TIME as it breaks many fewer things:

import locale
locale.setlocale(locale.LC_TIME, '')

Surely there will be a valid reason for this, but at least this could have been mentioned as a remark in the Python documentation for the %x directive.

查看更多
登录 后发表回答