Python:日期格式为%x(语言环境)的格式与预期不符 [英] Python: date formatted with %x (locale) is not as expected

查看:350
本文介绍了Python:日期格式为%x(语言环境)的格式与预期不符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

遵循Python的日期时间格式文档,我使用了%x格式代码,该代码应输出"区域设置的适当日期表示形式.".我希望这种表示形式"可以是Windows的短日期"或长日期"格式,但两者都不是. (我将短日期格式设置为d/MM/yyyy,长日期格式设置为dddd d MMMM yyyy,但输出为dd/MM/yy)

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)

这是怎么回事:Python文档,Python实现或我的期望? (以及如何解决?)

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

推荐答案

阅读 setlocale()文档,我知道Python并未使用默认的操作系统语言环境作为默认语言环境.要使用它,我必须使用以下命令启动我的模块:

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

或者,如果您只想重置语言环境的时间设置,请仅使用LC_TIME,因为它可以减少很多其他事情:

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

当然会有一个合理的原因,但是至少在Python文档中,%x指令中的注释可能已经提到了这一点.

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.

这篇关于Python:日期格式为%x(语言环境)的格式与预期不符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆