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

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

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest