Python:使用 %x(区域设置)格式化的日期与预期不符
我有一个日期时间对象,我想根据操作系统区域设置(例如在 Windows'7 区域和语言设置中指定)为其创建日期字符串。
遵循 Python 的 日期时间格式化文档,我使用了 < code>%x 格式代码应该输出“区域设置的适当日期表示。”。我希望这个“表示”是 Windows“短日期”或“长日期”格式,但它不是其中之一。 (我将短日期格式设置为 d/MM/yyyy ,将长日期格式设置为 dddd d MMMM yyyy ,但输出为 dd/MM/ yy)
这里有什么问题:Python 文档、Python 实现还是我的期望? (以及如何解决?)
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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
阅读 setlocale() 文档后,我了解到默认的操作系统区域设置Python 不使用它作为默认语言环境。 必须启动我的模块
:
要使用它,我 这个,但至少可以在 Python 文档中对 %x 指令的注释中提到这一点。
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:
Alternatively, if you intend to only reset the locale's time settings, use just
LC_TIME
as it breaks many fewer things: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.
您的语言环境是否在脚本中设置?如果您调用
locale.getlocale()
,结果是预期的吗?比较如下:请注意,
datetime
模块中存在错误,主要是由于底层 C 库中的错误。例如,在我的安装(最新的 OS X)上,格式化字符串%z
完全不可用。在 Windows 上,
setlocale()
可用的语言环境字符串的语法与 *nix 平台上的语法不同。 MSDN 上的列表。如果您只想将脚本设置为用户安装的任何默认区域设置(在我的中:英国英语),您只需在主脚本的开头执行此操作即可。不要在模块中执行此操作,因为它会覆盖全局变量:
Is your locale set in your script? If you call
locale.getlocale()
, is the result expected? Compare below: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: