Python pandas convert seconds to time (hh:mm)

Is it possible to convert a pandas dataframe column with total seconds in it to another column with time like hh:mm ?

In my mysql query I can do something like

SELECT SEC_TO_TIME(xxxx);

but the output is converted wrong in my pandas Dataframe, so I want to do the convertion from seconds to time with pandas instead of sql... I am playing around with the pd.to_timedelta function:

df['time'] = pd.Timedelta(Second(df['sec']))

But it is not working.

-edit-

Solved it! This was not working:

df['time'] = pd.to_datetime(df["sec"], unit='s')

but that was because the dtype of df["sec"] was wrong (it was an object type). I tried converting the column to float first and then the pd.to_datetime function and now I have what I want :) :

df['sec'] = df['sec'].astype('float64')
df['time'] = pd.to_datetime(df["sec"], unit='s')
3

1 Answer

This will convert the time to the YYYY-MM-DD hh:mm format:

df['time'] = pd.to_datetime(df['time'], unit='m')

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like