将派生的Timedelta添加到DateTime

时间:2016-11-22 18:07:59

标签: python-2.7 datetime dataframe timedelta

我正在尝试将NewTime作为OpenTimeCloseTime之间的中间位置添加到我的数据框df1,但它似乎无效。请参阅下面的代码。有什么想法吗?

>>> df1 = pd.DataFrame({'School': {0: 'ABC', 1: 'DEF', 2: 'GHI', 3: 'JKL', 4: 'MNO', 5: 'PQR'}, 'OpenTime': {0: '08:00:00.000', 1: '09:00:00.000', 2: '10:00:23.563', 3: '09:30:05.908', 4: '07:15:50.100', 5: '08:15:00.000'}, 'CloseTime': {0: '13:00:00.000', 1: '14:00:00.000', 2: '13:30:00.100', 3: '15:00:00.768', 4: '13:00:00.500', 5: '14:15:00.000'}, 'TimeZone':{0:'Europe/Vienna',1:'Europe/Brussels',2:'Europe/London',3:'Pacific/Auckland' ,4:'Asia/Seoul',5:'Europe/London'}})
>>> df1['OpenTime'] = pd.to_datetime(df1['OpenTime'])
>>> df1['CloseTime'] = pd.to_datetime(df1['CloseTime'])
>>> df1['Offset'] = df1.apply(lambda x:1/2*(x['CloseTime'] - x['OpenTime']), axis=1)
>>> df1
                CloseTime                OpenTime School          TimeZone   Offset 
0 2016-11-22 13:00:00.000 2016-11-22 08:00:00.000    ABC     Europe/Vienna   0 days  
1 2016-11-22 14:00:00.000 2016-11-22 09:00:00.000    DEF   Europe/Brussels   0 days   
2 2016-11-22 13:30:00.100 2016-11-22 10:00:23.563    GHI     Europe/London   0 days    
3 2016-11-22 15:00:00.768 2016-11-22 09:30:05.908    JKL  Pacific/Auckland   0 days    
4 2016-11-22 13:00:00.500 2016-11-22 07:15:50.100    MNO        Asia/Seoul   0 days    
5 2016-11-22 14:15:00.000 2016-11-22 08:15:00.000    PQR     Europe/London   0 days     
>>> df1['NewTime'] = df1['OpenTime'] + df1['Offset']
>>> df1
                CloseTime                OpenTime School          TimeZone   Offset                 NewTime
0 2016-11-22 13:00:00.000 2016-11-22 08:00:00.000    ABC     Europe/Vienna   0 days  2016-11-22 08:00:00.000
1 2016-11-22 14:00:00.000 2016-11-22 09:00:00.000    DEF   Europe/Brussels   0 days  2016-11-22 09:00:00.000 
2 2016-11-22 13:30:00.100 2016-11-22 10:00:23.563    GHI     Europe/London   0 days  2016-11-22 10:00:23.563
3 2016-11-22 15:00:00.768 2016-11-22 09:30:05.908    JKL  Pacific/Auckland   0 days  2016-11-22 09:30:05.908   
4 2016-11-22 13:00:00.500 2016-11-22 07:15:50.100    MNO        Asia/Seoul   0 days  2016-11-22 07:15:50.100   
5 2016-11-22 14:15:00.000 2016-11-22 08:15:00.000    PQR     Europe/London   0 days  2016-11-22 08:15:00.000    
>>> 

但是,如果我从1/2功能中移除lambda,这似乎正常。所以基本上我无法将timedelta乘以/除以任何数字。

对我来说使用lambda函数非常重要,因为我正在迭代地执行此操作以生成多次(不仅仅是中间时间)

1 个答案:

答案 0 :(得分:1)

你试过吗

df1['Offset'] = df1.apply(lambda x:((x['CloseTime'] - x['OpenTime']))/2, axis=1)

我刚刚在我的控制台中做到了这一点并且运行正常。我假设将1/2放在前面是引起问题的原因。