Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas convert seconds to time (hh:mm)

Tags:

python

pandas

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')
like image 673
Joost Avatar asked Feb 04 '23 10:02

Joost


1 Answers

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

df['time'] = pd.to_datetime(df['time'], unit='m')
like image 159
lukess Avatar answered Feb 16 '23 03:02

lukess