我在使用 Python 时仍然有点慢,所以除了文档中明显的内容等之外,我还没有弄清楚这一点。
我使用过 Django,他们通过模板标签添加了一些日期时间格式化选项,但是在常规 python 代码中 我怎样才能得到 12 小时 hour前导零?
有没有一种简单的方法可以做到这一点?我正在查看“strftime()”的 2.5 和 2.6 文档,但似乎没有针对这种情况的格式化选项。
我应该使用其他东西吗?
请随意添加文档中不明显的任何其他时间格式提示。 =)
datetime
内置的任何东西都无法做到这一点。你需要使用类似的东西:
datetime.time(1).strftime('%I:%M%p').lstrip('0')
附录
正如@naktini 指出的那样,这是为使用这个特定的 strftime
参数而定制的。不幸的是,如果 strftime
参数的内容未知或未指定(例如外部参数),则没有通用解决方案,因为它变成了“按我的意思做,而不是按我说的做”的问题。
因此,鉴于您必须知道 strftime
参数中的内容,在更复杂的情况下,您可以将其作为部分解决:
tval = datetime.time(1)
tval_str = (tval.strftime('%A, %B ') + tval.strftime('%d').lstrip('0')
+ tval.strftime(' %Y, ') + tval.strftime('%I:%M').lstrip('0')
+ tval.strftime('%p').lower())
或使用 re
模块:
tval = datetime.time(1)
tval_str = re.sub(r"^0|(?<=\s)0", "",
re.sub(r"(?<=[0-9])[AP]M", lambda m: m.group().lower(),
tval.strftime('%A, %B %d %Y, %I:%M%p')))
也就是说,请记住,如果 "%p"
术语为您提供大写字母,可能是因为用户将他们的语言环境设置为以这种方式工作,并且通过更改大小写您正在覆盖用户偏好,有时会导致错误报告。此外,用户可能需要“am”或“pm”以外的其他内容,例如“a.m”。和“下午”。另请注意,对于不同的语言环境,这些是不同的(例如,en_US
语言环境为 %p
提供 AM
或 PM
,但de_DE
给出 am
或 pm
),您可能无法获得您假设的编码中的字符。
来自 documentation on strftime behavior :
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).
因此,简而言之,如果您认为需要覆盖语言环境设置,请确保您有充分的理由这样做,这样您就不会最终产生新的错误。
我是一名优秀的程序员,十分优秀!