2017-08-26 89 views
2
>>> 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小時的格式?datetime.strptime()AM PM規範

12小時制:

上2017年7月4日12點24分十一秒後很快午夜將被指定爲12時24分十一秒

12時24分十一秒在2017-07-04中午不久後也會指定爲12:24:11

爲什麼假定它會在午夜之後不久轉換爲時間?

我希望它會發出警告或錯誤,因爲我的時間字符串不夠具體。

+0

@roganjosh我明白這一點。我剛剛更新了這個問題,以便更清楚我擔心的是什麼。 – abc

+1

''2017-07-04 12:24:11''沒有足夠的信息來判斷它是AM還是PM。我想對於一個十二小時的格式,它必須默認爲某種東西。 – wwii

+0

只需使用「%H」作爲24小時格式 – ChristianFigueroa

回答

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功能隨着你的修改,然後適當地分配它產生一些更無縫的東西,但我不知道這是多麼明智。那是什麼脂肪酶叫猴子補丁?

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-ho你的時鐘)作爲零填充的十進制數字。