0

Starting and end times

I need to calculate the time difference in minutes and create a separate entry in the data frame in minutes

I tried and got the following error

2nd try

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • 2
    Please read https://stackoverflow.com/help/how-to-ask and https://stackoverflow.com/help/minimal-reproducible-example. After that please update your question that it can help other readers, too. – buhtz Sep 07 '21 at 12:10
  • 1
    Please include any relevant information [as text directly into your question](https://stackoverflow.com/editing-help), do not link or embed external images of source code or data. Images make it difficult to efficiently assist you as they cannot be copied and offer poor usability as they cannot be searched. See: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/15497888) – Henry Ecker Sep 12 '21 at 06:38
  • 1
    If you need assistance formatting a small sample of your DataFrame as a copyable piece of code for SO see [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15497888). – Henry Ecker Sep 12 '21 at 06:38
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 12 '21 at 16:13

2 Answers2

0
start_time = pd.to_datetime(df['Start time'].astype(str)) 
end_time = pd.to_datetime(df['End time'].astype(str))
df['diff'] = end_time.sub(start_time).dt.total_seconds().div(60)

I have stored values in seperate variable start_time and end_time to do not override dataframe (i.e. Without convering datatype of columns to datetime). Otherwise you can directly use it without saving in variables.

Rinshan Kolayil
  • 1,111
  • 1
  • 9
  • 14
0

Use pd.to_datetime:

Minimal Reproducible Example:

df = pd.DataFrame({'Start time': ['07:15:00'], 'End time': ['10:40:00']})
df['Diff time'] = pd.to_datetime(df['End time']) \
                        .sub(pd.to_datetime(df['Start time'])) \
                        .dt.total_seconds().div(60)

Output:

>>> df
  Start time  End time  Diff time
0   07:15:00  10:40:00      205.0
Corralien
  • 109,409
  • 8
  • 28
  • 52