Python:使用%x(语言环境)格式化的日期不符合预期

Rab*_*ski 3 python datetime locale internationalization

我有一个datetime对象,我想根据操作系统区域设置创建一个日期字符串(例如在Windows'7区域和语言设置中指定).

在Python的日期时间格式文档之后,我使用了%x应该输出" Locale的适当日期表示 " 的格式代码.我希望这种"表示"可以是Windows"短日期"或"长日期"格式,但它不是一种.(我将短日期格式设置为d/MM/yyyy和长日期格式dddd d MMMM yyyy,但输出是dd/MM/yy)

这里有什么问题:Python文档,Python实现或我的期望?(以及如何修复?)

Rab*_*ski 7

在阅读了setlocale()文档之后,我明白Python没有使用默认的OS语言环境作为默认语言环境.要使用它,我必须启动我的模块:

import locale
locale.setlocale(locale.LC_ALL, '')
Run Code Online (Sandbox Code Playgroud)

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, '')
Run Code Online (Sandbox Code Playgroud)

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.


chr*_*yss 5

您的语言环境是否在脚本中设置?如果你打电话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'
Run Code Online (Sandbox Code Playgroud)

请注意,datetime模块中存在错误,主要是因为底层C库中存在错误.例如,在我的安装(最新的OS X)上,格式化字符串%z完全不可用.

在Windows上,语言环境字符串的语法可用于setlocale()遵循与*nix平台不同的语法.MSDN上有一个列表.

如果您只是希望将脚本设置为用户安装的任何默认语言环境(在我的:英国英语),您只需在主脚本的开头执行此操作.不要在模块中执行,因为它会覆盖全局变量:

>>> locale.setlocale(locale.LC_ALL, "")
'en_GB.UTF-8'
Run Code Online (Sandbox Code Playgroud)