datetime.strptime()AM PM规范

时间:2017-08-26 19:03:03

标签: python python-2.7

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

为什么上述转换时间为0小时?如果我的下午12:24:11以12小时格式表示怎么办?

12小时格式:

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

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

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

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

3 个答案:

答案 0 :(得分:2)

这种行为一定是设计决定。以下是_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函数然后适当地分配它以产生更加无缝的东西,但我不知道它是多么明智。是ppl称猴子修补的吗?

答案 1 :(得分:1)

日期格式是获得上述格式的原因0.请参阅文档以获取正确的格式。使用%I表示12小时格式,使用%H表示24小时格式 - https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

答案 2 :(得分:0)

如果您使用%I,那么:

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

如果你使用%H

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

strftime and strptime Behavior
注意: - %I用于小时(12小时制)作为零填充十进制数,而%H用于小时(24小时)小时时钟)作为零填充十进制数。