Python: date formatted in% x (locale) does not meet expectations

I have a datetime object for which I want to create a date string in accordance with the OS locale settings (as indicated, for example, in the Windows7 area and language settings).

Following the Python datetime formatting documentation , I used a format code %xthat should output "Corresponding date representation in locales." I expect this "view" to be either the Windows "short date" format or the "Long date" format, but it is not one. (I have a short date format set to d/MM/yyyy, and a long date format is dddd d MMMM yyyy, but the output dd/MM/yy)

What is wrong here: Python documentation, Python implementation, or my expectations? (and how to fix?)

+3
source share
2 answers

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

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

Alternatively, if you intend to use only reset locale time settings, use only LC_TIMEas it breaks much less things:

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

Of course, there will be a good reason for this, but at least it could be mentioned as a remark in the Python documentation for the% x directive.

+7

script? locale.getlocale(), ? :

>>> 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'

, datetime , - C. , ( X) %z .

Windows locale, setlocale(), , * nix. , MSDN.

script , ( ), script. , :

>>> locale.setlocale(locale.LC_ALL, "")
'en_GB.UTF-8'
+5

Source: https://habr.com/ru/post/1758681/


All Articles