How to convert timedelta in data frame to datetime

Question:

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

Asked By: Grzegorz Z

||

Answers:

not sure how you data is stored.. but you could try something like this:

# Example DataFrame
data = {'time1': ['0 days 00:00:21', '0 days 00:01:15', '0 days 00:02:45'],
        'time2': ['0 days 00:00:35', '0 days 00:00:50', '0 days 00:03:10']}
df = pd.DataFrame(data)

# Convert columns to timedelta objects
df[['time1', 'time2']] = df[['time1', 'time2']].apply(pd.to_timedelta)

# Extract time component and convert to string
df[['time1', 'time2']] = df[['time1', 'time2']].applymap(lambda x: x.seconds)

# Convert seconds to hh:mm:ss format
df[['time1', 'time2']] = df[['time1', 'time2']].applymap(lambda x: pd.to_datetime(x, unit='s').time())

print(df)`
Answered By: Max888

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())