Home > Net >  Covert time mm:ss.ms to seconds
Covert time mm:ss.ms to seconds

Time:10-09

I have a time column in my dataframe that has values like 20:14.4 and I am trying to convert it to seconds.

I have tried df['time'].str.split(':').apply(lambda x: int(x[0]) * 60 int(x[1])) but the milliseconds at the end would not let it work. The datatype is object. Kindly help. enter image description hereenter image description here

CodePudding user response:

what is the datatype of the time column?

pd.to_timedelta(df['time']).dt.total_seconds()

to get rid of the fraction part

pd.to_timedelta(df['time']).dt.total_seconds().astype(int)

CodePudding user response:

Finally found a solution to the problem enter image description here

df['mins'] = pd.to_datetime(df['Time'], format='%M:%S.%f').dt.minute

df['sec'] = pd.to_datetime(df['Time'], format='%M:%S.%f').dt.second

df['Time(s)'] = ((df['mins']*60) df['sec'])

  • Related