Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas column convert minutes to second

I have pandas like below:

    Runner  time
1   A      3.05.3   #( 3 minute 5 second and 3 millisecond)
2   B      2.50.2   #( 2 minute 50 second and 2 millisecond)

Actually I want to compare the time so I want to change to time column to second unit or millisecond unit.
How can I do it in pandas?
I am thinking if can I strptime?

like image 677
Kenneth Yeung Avatar asked Dec 01 '25 06:12

Kenneth Yeung


1 Answers

You can use datetime.timedelta to perform this calculation for you. For convenience, you can wrap this in a function and apply via pd.Series.apply.

from datetime import timedelta

df = pd.DataFrame({'Runner': ['A', 'B'],
                   'time': ['3.05.3', '2.50.2']})

def seconder(x):
    mins, secs, millis = map(float, x.split('.'))
    td = timedelta(minutes=mins, seconds=secs, milliseconds=millis)
    return td.total_seconds()

df['seconds'] = df['time'].apply(seconder)

print(df)

  Runner    time  seconds
0      A  3.05.3  185.003
1      B  2.50.2  170.002
like image 74
jpp Avatar answered Dec 05 '25 00:12

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!