Home>

The following table is created using pandas DataFrame.

'ID date time
0 A 2020-04-11 12:36:19.860000
1 B 2020-04-11 12:36:19.960000
2 C 2020-04-11 12:36:20
3 D 2020-04-11 12:36:20.150000
4 E 2020-04-11 12:36:20.260000


I want to convert the time sequence to datetime type, and when I use to_datetime(), the following error message appears.
Probably there are some elements where the decimal point disappears, such as the time column, 12:36:20 in the 2nd line, and I think it would be fine to add the decimal point to these, but I have no idea of ​​implementation.
I would appreciate it if you could teach me how to deal with it.

ValueError: time data '12:36:20' does not match format'%H:%M:%S.%f' (match)
Applicable source code
pd.to_datetime(df['time'], format='%H:%M:%S.%f').dt.time
Usage environment

python 3.7
pandas 1.0.1

  • Answer # 1

    Isn't it all right if the format is not specified?

    df = pd.DataFrame(
        {
            "ID": ["A", "B", "C", "D", "E"],
            "Date": ["2020-04-11", "2020-04-11", "2020-04-11", "2020-04-11", "2020-04-11"],
            "Time": [
                "12:36:19.860000",
                "12:36:19.960000",
                "12:36:20",
                "12:36:20.150000",
                "12:36:20.260000",
            ],
        }
    )
    time = pd.to_datetime(df["date"] + "" + df["time"])
    print(time)
    # 0 2020-04-11 12:36:19.860
    # 1 2020-04-11 12:36:19.960
    # 2 2020-04-11 12:36:20.000
    # 3 2020-04-11 12:36:20.150
    # 4 2020-04-11 12:36:20.260
    # dtype: datetime64[ns]