I have a CSV file with columns date
, time
. I want to calculate row-by-row the time difference time_diff
in the time column. I wrote the following code but it's incorrect.
Here is my code and at bottom, my CSV file:
#def time_diff(x):
date_array = []
date_array.append(pd.to_datetime(data['date'][0]).date())
start = []
end = []
temp_date = pd.to_datetime(data['date'][0]).date()
start.append(pd.to_datetime(data['time'][0], format='%H:%M:%S').time())
for i in range(len(data['date'])):
cur_date = pd.to_datetime(data['date'][i]).date()
if( cur_date > temp_date):
end.append(pd.to_datetime(data['time'][i-1], format='%H:%M:%S').time())
start.append(pd.to_datetime(data['time'][i], format='%H:%M:%S').time())
date_array.append(cur_date)
temp_date = cur_date
end.append(pd.to_datetime(data['time'][len(data['date'])-1], format='%H:%M:%S').time())
if start <= end:
return end - start
else:
end += timedelta(1) # +day
assert end > start
return end - start
for i in range(len(date_array)):
s_time = datetime.datetime.combine(date_array[i],start_time[i])
e_time = datetime.datetime.combine(date_array[i], end_time[i])
timediff = (e_time - s_time)
My CSV file:
First column and second column are date
and time
. Third column shows expected time_diff
in hours.