从Python日期/时间获取“2:35pm”而不是“02:35pm”?

2024-04-24 23:25:22 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

虽然我偏爱Mike DeSimone's answer,但出于投票目的,我认为这可能是一个有价值的贡献。。。

Django项目在django/utils/dateformat.py (trunk)中包含一个“PHP兼容”日期格式类。它的用法类似于so(shell示例):

>>> import datetime
>>> from django.utils.dateformat import DateFormat
>>> d = datetime.datetime.now()
>>> df =  DateFormat(d)
>>> df.format('g:ia') # Format for Hour-no-leading-0, minutes, lowercase 'AM/PM'
u'9:10a.m.'

它满足了这里的要求,可能值得包括在您的项目中。这样的话,我会说你应该核实许可证允许这样的使用。。。欢迎提出任何澄清意见。

任何内置的datetime都不能做到这一点。您需要使用以下内容:

datetime.time(1).strftime('%I:%M%p').lstrip('0')

附录

正如@naktinis指出的,这是为使用这个特定的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"术语给您提供大写字母,可能是因为用户将其区域设置为以这种方式工作,并且通过更改大小写,您将覆盖用户首选项,这有时会导致错误报告。此外,用户可能需要“a m”或“pm”以外的其他内容,例如“a.m.”和“p.m.”。还要注意的是,对于不同的区域设置,它们是不同的(例如,en_US区域设置给出AMPM表示%p,但是de_DE给出ampm),并且您可能无法在假定的编码中获得字符。

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

所以,简而言之,如果你认为你需要重写语言环境设置,请确保你有一个很好的理由来解释,这样你就不会只是制造新的bug。

这个问题已经得到了回答,但是在使用glibc因为Python's ^{} uses the c library's ^{}而使用.strftime("%-I:%M%P")的linux平台上,可以从Python datetime直接获得“2:35pm”。

>>> import datetime
>>> now = datetime.datetime.now()
datetime.datetime(2012, 9, 18, 15, 0, 30, 385186)
>>> now.strftime("%-I:%M%P")
'3:00pm'
>>> datetime.time(14, 35).strftime("%-I:%M%P")
'2:35pm'

strftime glibc notes on "-"

相关问题 更多 >