Parsing string to datetime while accounting for AM/PM in pandas

后端 未结 2 1872
误落风尘
误落风尘 2021-01-19 10:48

I am trying to parse a string in this format \"2018 - 07 - 07 04 - AM\" to pandas datetime using strftime format. However, It seems to me the format doesn\'

相关标签:
2条回答
  • 2021-01-19 11:13

    In my case, I got an error message when trying the proposed solutions:

     ValueError: unconverted data remains: PM
    

    This was solved by setting the locale to en_US.

    0 讨论(0)
  • 2021-01-19 11:21

    Since you're parsing a 12-hour time format, you will need %I instead of %H, otherwise the %p specifier has no effect.

    pd.to_datetime("2018 - 07 - 07 04 - PM", format='%Y - %m - %d %I - %p')
    Timestamp('2018-07-07 16:00:00')
    

    This behaviour is documented in the docs:

    When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

    0 讨论(0)
提交回复
热议问题