Adding,subtracting Datetime.time Columns Pandas
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
Solution 1:
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
Solution 2:
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'))
Solution 3:
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]')
Post a Comment for "Adding,subtracting Datetime.time Columns Pandas"