Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time difference between two columns in Pandas

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

like image 898
zaddyn00b Avatar asked Nov 24 '25 23:11

zaddyn00b


1 Answers

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))
like image 168
jezrael Avatar answered Nov 28 '25 16:11

jezrael



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!