adding,subtracting datetime.time columns pandas

Viewed 6170

I have following dataframe

flight_departure   arrival_at_desination   boarding  total_flight_time   total_flight_time/2    time_to_collect_bags
0:00                     4:00               23:30           4:00                  2:00                     4:30
9:00                     14:30              8:30            5:30                  2:45                      15:00

flight_departure- 0:00 signifies 12:00 AM
arrival_at_desination- 4:00 signifies 4 AM
boarding = flight_departure-30 minutes(23:30)
total_flight_time=arrival_at_desination-flight_departure(4 hours)

total_flight_time/2-calculates hald time(2 hours in this case)
time_to_collect_bags=arrival_at_desination+30 minutes(4:30AM)

When I try to do the following

df['arrival_at_desination']-df['flight_departure']

It gives me following error

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

how should I subtract two datetime.time columns?

3 Answers

You have to convert to datatime format to convert try this

arrival = pd.to_datetime(df['arrival_at_desination'])
dept = pd.to_datetime(df['flight_departure'])
diff = arrival - dept

This is what I get, hope this help,

0   -1 days +20:00:00
1   -1 days +18:30:00

Else add date to the data, concatenate with time and perform the above

In general, it's not possible to subtract two times without date information (what if the arrival is at 1am and the departure is 11pm?). If you're assuming they're on the same date, and the time of arrival is always greater than the time of departure, you could do the following. It's not pretty and hopefully someone comes along with a better answer.

(pd.to_datetime(df.arrival_at_desination.astype(str), format='%H:%M:%S') -
    pd.to_datetime(df.flight_departure.astype(str), format='%H:%M:%S'))

I found that to make this work (python3.68), you need to combine the time with a date -- real or fake.

import pandas as pd


df = pd.DataFrame(columns=['to','fr','ans'])

date = "1-1-01 "
tmp = pd.Series(['13:03:12','11:57:18','10:07:47'])
tm =pd.to_datetime(date+tmp, format='%d-%m-%y %H:%M:%S')

tmp = pd.Series(['13:02:12','10:57:18','10:07:22'])
tm2 =pd.to_datetime(date+tmp, format='%d-%m-%y %H:%M:%S')

df.to = tm2
df.fr = tm

(df.fr-df.to)
#if you want this as seconds -- which for my applications has been more useful.
(df.fr-df.to).astype('timedelta64[s]')
Related