2017-08-26 5 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時間形式で表したらどうなりますか? 12時間形式でdatetime.strptime()AM PM指定

:真夜中の12時24分11秒

12時24分11秒として指定されます後すぐに2017年7月4日に

12時24分11秒すぐ後の2017-07-04にも正午以降に指定されます.12:24:11

なぜ真夜中後に時間を想定して変換しましたか?

私の時間文字列が十分ではないため、警告またはエラーが表示されることを期待していました。

+0

@roganjosh私はそれを理解しています。私は心配していることをより明確にするように質問を更新しました。 – abc

+1

'' 2017-07-04 12:24:11''には、AMかPMかを区別するのに十分な情報が含まれていません。私は十二時間のフォーマットのために何かにデフォルト設定しなければならないと思う。 – wwii

+0

24時間形式の場合は "%H"を使用してください – 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: 

の関連部分は、私はあなたが手足に出て行って、_strptime機能を再現することができ想像..

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) 

ですあなたの修正を加えて、それを適切に割り当てて、もう少しシームレスなものを作り出してください。しかし、それがどれほど賢明かはわかりません。それはpplがサルのパッチを当てるのですか?

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時間制)のためであります0パディング10進数として%Hは時間(24-ho URクロック)をゼロ詰めの10進数として出力します。

関連する問題