Joost
Joost

Reputation: 490

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

Upvotes: 8

Views: 29993

Answers (2)

Ali Raza
Ali Raza

Reputation: 1

def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
     
    return "%d:%02d:%02d" % (hour, minutes, seconds)

n = 12345
print(convert(n))

Upvotes: -1

lukess
lukess

Reputation: 964

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

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

Upvotes: 10

Related Questions