Rahul
Rahul

Reputation: 775

Adding derived Timedelta to DateTime

I am trying to add NewTime as the mid-time between OpenTime and CloseTime to my dataframe df1 and it seems to be not working. Please see the code below. Any ideas?

>>> 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    
>>> 

However if I remove 1/2 from my lambda function this seems to be working. So essentially I am not able to multiply/divide timedelta with any number.

It is quite critical for me to use lambda function because I am doing this iteratively to generate many times (not just midtime)

Upvotes: 0

Views: 57

Answers (1)

gold_cy
gold_cy

Reputation: 14236

Did you try

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

I just did that in my console and it worked fine. I'm assuming that putting the 1/2 in front is what is causing the problem.

Upvotes: 1

Related Questions