pythondataframetimestring-conversionminute

Python: Pandas Dataframe -- Convert String Time Column in mm:ss Format to Total Minutes in Float Format


Let's say I have a python dataframe with a time related column called "Time". Inside this column there are strings that represent minutes and seconds. For example, the first row value 125:19 represents 125 minutes and 19 seconds. Its datatype is a string.

I want to convert this value to total minutes in a new column "Time_minutes". So 125:19 should become 125.316666666667 which should be a float datatype.

Along a similar vein if the value is 0:00 then the corresponding "Time_minutes" column should show 0 (float datatype).

I've done this in SQL using lambdas and index functions. But is there an easier/more straightforward way to do this in python?


Solution

  • One of possible solution, use .str.split:

    df["Converted"] = (s := df["Time"].str.split(":")).str[0].astype(float) + (s.str[1].astype(float) / 60)
    print(df)
    

    Prints:

         Time   Converted
    0  125:19  125.316667
    1    0:00    0.000000
    2    0:30    0.500000