pythondataframedatetimetimedelta

How to convert timedelta in data frame to datetime


I have couple columns in df with avg time, example "0 days 00:00:21". I want convert all columns to datetime.time format "hh:mm:ss" without "0 days". How can I do this?

my df


Solution

  • Should be fine with that code

    For 4 columns, u can create a list of column names that u want to change. After that, put into for loop to iterate all column names that u want to change. It'll convert columns.

    column_names = ["first","second","third","fourth"]
    
    for name in column_names:
        df[name] = df[name].dt.seconds.apply(lambda x: pd.to_datetime(x, unit='s').time())