How to define format when using pandas to_datetime?

前端 未结 2 1449
闹比i
闹比i 2020-12-16 12:29

I want to plot RESULT vs TIME based on a testresult.csv file that has following format, and I have trouble to get the TIME column\'s datatype defined properly.<

2条回答
  •  没有蜡笔的小新
    2020-12-16 13:02

    The format you are passing is invalid. The dash between the % and the I is not supposed to be there.

    df['TIME'] = pd.to_datetime(df['TIME'], format="%m/%d/%Y %I:%M:%S %p")
    

    This will convert your TIME column to a datetime.


    Alternatively, you can adjust your read_csv call to do this:

    pd.read_csv('testresult.csv', parse_dates=['TIME'], 
        date_parser=lambda x: pd.to_datetime(x, format='%m/%d/%Y %I:%M:%S %p'))
    

    Again, this uses the appropriate format with out the extra -, but it also passes in the format to the date_parser parameter instead of having pandas attempt to guess it with the infer_datetime_format parameter.

提交回复
热议问题