Search code examples
pythonpandastimetype-conversioncalculated-columns

Convert Time in hh:mm:ss Format to Total Minutes in pandas


I have the following sample input table below. The Time column is in the format of hh:mm:ss or hours, minutes, and seconds.

Name Time
Jim 1:33:04
Chrissy 0:06:39
Billy 10:00:02

The code to create the above table is:

import pandas as pd
df = pd.DataFrame({'Name':["Jim","Chrissy","Billy"], 'Time':['1:33:04', '0:06:39', '10:00:02']})

I want to create a new column called "_timemin" that converts the Time column to minutes. For example, 10:00:02 would be equal to 600.03 minutes.

I tried to apply the following code but it didn't work:

df['_timemin'] = df['Time'].str.split(':').apply(lambda x: (int(x[0])*60) + int(x[1])) + int(x[2]/60)  

... the above code produces the error:

NameError: name 'x' is not defined

Solution

  • Your expression df['_timemin'] = df['Time'].str.split(':').apply(lambda x: (int(x[0])*60) + int(x[1])) + int(x[2]/60) has three issues:

    1. Does not close the apply method
    2. Applies (closes lambda x) to first two elements (x[0] and x[1]) only
    3. Does not convert string x[2] to numerical data type before division

    Here are two options:

    df['_timemin'] = df['Time'].str.split(':').apply(lambda x: int(x[0]) * 60 + int(x[1]) + int(x[2]) // 60) floor (or integer) division to minute

    df['_timemin'] = df['Time'].str.split(':').apply(lambda x: int(x[0]) * 60 + int(x[1]) + int(x[2]) / 60) floating minutes