添加,减去datetime.time列熊猫

时间:2019-01-13 04:42:49

标签: python pandas time-series

我有以下数据框

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)

当我尝试执行以下操作

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

它给了我以下错误

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

如何减去两个datetime.time列?

4 个答案:

答案 0 :(得分:2)

您必须转换为datatime格式才能进行转换

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

这就是我得到的,希望有帮助,

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

否则将日期添加到数据中,并与时间连接并执行上述操作

答案 1 :(得分:0)

通常,没有日期信息就不可能减去两次(如果到达时间是凌晨1点而出发时间是11pm,该怎么办?)。如果您假设他们在同一日期,并且到达时间始终大于出发时间,则可以执行以下操作。它不是很漂亮,希望有人能提供更好的答案。

(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'))

答案 2 :(得分:0)

我发现要执行此操作(python3.68),您需要将时间与日期结合使用-真实的或假的。

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]')

答案 3 :(得分:-1)

嗯.... sub()方法可以解决这个问题吗?你尝试了吗?