Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, “month/day/year” versus “day/month/year”), and the output may contain Unicode characters encoded using the locale’s default encoding (for example, if the current locale is js_JP, the default encoding could be any one of eucJP, SJIS, or utf-8; use locale.getlocale() to determine the current locale’s encoding).
虽然我偏爱Mike DeSimone's answer,但出于投票目的,我认为这可能是一个有价值的贡献。。。
Django项目在django/utils/dateformat.py (trunk)中包含一个“PHP兼容”日期格式类。它的用法类似于so(shell示例):
它满足了这里的要求,可能值得包括在您的项目中。这样的话,我会说你应该核实许可证允许这样的使用。。。欢迎提出任何澄清意见。
任何内置的
datetime
都不能做到这一点。您需要使用以下内容:附录
正如@naktinis指出的,这是为使用这个特定的
strftime
参数而定制的。不幸的是,如果strftime
参数的内容未知或未指定(例如外部参数),则没有通用的解决方案,因为它变成了一个“按我的意思做,而不是按我说的做”问题。因此,考虑到您必须知道
strftime
参数中的内容,在更复杂的情况下,您可以将其作为部分解决:或者使用
re
模块:也就是说,请记住,如果
"%p"
术语给您提供大写字母,可能是因为用户将其区域设置为以这种方式工作,并且通过更改大小写,您将覆盖用户首选项,这有时会导致错误报告。此外,用户可能需要“a m”或“pm”以外的其他内容,例如“a.m.”和“p.m.”。还要注意的是,对于不同的区域设置,它们是不同的(例如,en_US
区域设置给出AM
或PM
表示%p
,但是de_DE
给出am
或pm
),并且您可能无法在假定的编码中获得字符。从documentation on strftime behavior:
所以,简而言之,如果你认为你需要重写语言环境设置,请确保你有一个很好的理由来解释,这样你就不会只是制造新的bug。
这个问题已经得到了回答,但是在使用glibc因为Python's ^{} uses the c library's ^{} 而使用
.strftime("%-I:%M%P")
的linux平台上,可以从Python datetime直接获得“2:35pm”。见strftime glibc notes on "-"。
相关问题 更多 >
编程相关推荐