gpt4 book ai didi

python - datetime.strptime() AM PM 规范

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:54 24 4
gpt4 key购买 nike

>>> datetime.strptime('2017-07-04 12:24:11', "%Y-%m-%d %I:%M:%S")
datetime.datetime(2017, 7, 4, 0, 24, 11)

为什么上面的转换得到一个小时的 0 ?如果我指的是 12 小时格式的下午 12:24:11 呢?

12 小时格式:

2017-07-04 午夜后不久的 12:24:11 将被指定为 12:24:11

2017-07-04 中午过后的 12:24:11 也将​​指定为 12:24:11

为什么它会在午夜后不久假设并将其转换为时间?

我希望它会给出警告或错误,因为我的时间字符串不够具体。

最佳答案

该行为一定是设计决定。这是 _strptime function in \Lib\_strptime.py 的相关部分

    elif group_key == 'I':
hour = int(found_dict['I'])
ampm = found_dict.get('p', '').lower()
# If there was no AM/PM indicator, we'll treat this like AM
if ampm in ('', locale_time.am_pm[0]):
# We're in AM so the hour is correct unless we're
# looking at 12 midnight.
# 12 midnight == 12 AM == hour 0
if hour == 12:
hour = 0
elif ampm == locale_time.am_pm[1]:
# We're in PM so we need to add 12 to the hour unless
# we're looking at 12 noon.
# 12 noon == 12 PM == hour 12
if hour != 12:

你可以自定义它来做你想做的事..

class foo(datetime.datetime):
"""foo(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

The year, month and day arguments are required. tzinfo may be None, or an
instance of a tzinfo subclass. The remaining arguments may be ints.
"""

@classmethod
def strptime(cls, datestring, fmt):
if '%I' in fmt and not any(attr in datestring for attr
in ('AM', 'am', 'PM', 'pm')):
print('Ambiguous datestring with twelve hour format')
#raise ValueError('Ambiguous datestring with twelve hour format')
return super().strptime(datestring, fmt)

我想您可以大胆尝试并通过您的修改重现 _strptime 函数,然后适本地分配它以产生更无缝的东西,但我不知道这有多明智。这就是人们所说的猴子补丁吗?

关于python - datetime.strptime() AM PM 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com