pythonpandastimedatetime-conversion

How to convert time data which saved as integer type in csv file into datetime in python


I have csv file and in 'Time' column, time data is saved in integer type like

7
20
132
4321
123456
...

and I have to convert datatime in python like

00:00:07
00:00:20
00:01:32
00:43:21
12:34:56
...

and size of data is almost 250,000,,,

How do I convert this number to a datetime?

I tried but failed

change_time=str(int(df_NPA_2020['TIME'])).zfill(6)
change_time=change_time[:2]+":"+change_time[2:4]+":"+change_time[4:]
change_time

and

change_time=df_NPA_2020['ch_time'] = df_NPA_2020['TIME'].apply(lambda x: pd.to_datetime(str(x), format='%H:%M:%S'))

Solution

  • You're almost there. You have to use .astype(str) method to convert a column as string and not str(df_NPA_2020['TIME']). The latter is like a print.

    df_NPA_2020['ch_time'] = pd.to_datetime(df_NPA_2020['TIME'].astype(str).str.zfill(6), format='%H%M%S').dt.time
    print(df_NPA_2020)
    
    # Output
         TIME             ch_time
    0       7 1900-01-01 00:00:07
    1      20 1900-01-01 00:00:20
    2     132 1900-01-01 00:01:32
    3    4321 1900-01-01 00:43:21
    4  123456 1900-01-01 12:34:56