3

How can I subtract the time between two columns and convert it to minutes

         Date Time Ordered Time Delivered
0  1/11/19   9:25:00 am    10:58:00 am
1  1/11/19  10:16:00 am    11:13:00 am
2  1/11/19  10:25:00 am    10:45:00 am
3  1/11/19  10:45:00 am    11:12:00 am
4  1/11/19  11:11:00 am    11:47:00 am

I want to subtract the Time_delivered - Time_ordered to get the minutes the delivery took.

df.time_ordered = pd.to_datetime(df.time_ordered)

This doesn't output the correct time instead it adds today's date the time

Umar.H
  • 22,559
  • 7
  • 39
  • 74
zaddyn00b
  • 201
  • 4
  • 13
  • 2
    Please post the data as text and not an image. No one can copy it into python if its an image. Also in your image your column name is `Time Ordered` but in your code you imply it is `time_ordered`... – Dan Dec 05 '19 at 10:31
  • 1
    What does `pd.to_datetime(df.["Date"] + df["Time Ordered"])` give you? – Dan Dec 05 '19 at 10:32
  • Does this answer your question? [Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes](https://stackoverflow.com/questions/22923775/calculate-pandas-dataframe-time-difference-between-two-columns-in-hours-and-minu) – Trenton McKinney Aug 23 '20 at 01:12

3 Answers3

5

Convert both time columns to datetimes, get difference, convert to seconds by Series.dt.total_seconds and then to minutes by division by 60:

df['diff'] = (pd.to_datetime(df.time_ordered, format='%I:%M:%S %p')
                .sub(pd.to_datetime(df.time_delivered, format='%I:%M:%S %p'))
                .dt.total_seconds()
                .div(60))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

Try to_datetime()

df = pd.DataFrame([['9:25:00 AM','10:58:00 AM']],
                  columns=['time1', 'time2'])

print(pd.to_datetime(df.time2)-pd.to_datetime(df.time1))

Output:

01:33:00
davidbilla
  • 2,120
  • 1
  • 15
  • 26
0

another way is using np.timedelta64

print(df)
     Date Time Ordered Time Delivered
0  1/11/19   9:25:00 am    10:58:00 am
1  1/11/19  10:16:00 am    11:13:00 am
2  1/11/19  10:25:00 am    10:45:00 am
3  1/11/19  10:45:00 am    11:12:00 am
4  1/11/19  11:11:00 am    11:47:00 am

   df['mins'] =  (
    pd.to_datetime(df["Date"] + " " + df["Time Delivered"])
    - pd.to_datetime(df["Date"] + " " + df["Time Ordered"])
) / np.timedelta64(1, "m")
output:
print(df)
   Date     Time Ordered   Time Delivered mins
0  1/11/19   9:25:00 am    10:58:00 am  93.0
1  1/11/19  10:16:00 am    11:13:00 am  57.0
2  1/11/19  10:25:00 am    10:45:00 am  20.0
3  1/11/19  10:45:00 am    11:12:00 am  27.0
4  1/11/19  11:11:00 am    11:47:00 am  36.0
Umar.H
  • 22,559
  • 7
  • 39
  • 74