I need to calculate the difference between two dates but I need to do it for each pair of rows, then save it in an excel file,for example :
df:
B
0 2018-02-11 12:14:25 #1st row
1 2018-02-11 12:15:30 #2nd row
2 2018-02-11 12:15:54 #3rd row
3 2018-02-11 12:16:11 #4th row
My program needs to subtract the second row from the first row and the forth row from the third row.
this is my code so far:
import pandas as pd
df = pd.read_excel('test.xlsx',header=0, index= False)
sub ='chan_avail'
df["Indexes"]= df["A"].str.find(sub)
df["B"]=df['Time'].where(df['Indexes'] == 0)
df1 = df.dropna(subset=['B'])
#print(df1)
df2 = df1.reset_index(drop=True, inplace=True)
df1['B'] = pd.to_datetime(df1['B'])
#print(df1)
xx=len(df1.index)
for i in range(xx):
if i % 2 == 0:
print('!!') #test
df1['diffB'] = df1['B'] - df1['B'].shift(-1)
print(df1)
df1.to_excel('output.xlsx', 'Sheet1', index=True)
what I intented to do was calculating the difference between rows if the index is pair but it did not work.
Also when I tried to save the difference in time in excel I got 0 but in the consol of python I got the correct value, but if i add df1['diffB'] = pd.to_datetime(df1['diffB'])
I get an incorrect result.
Thank you for your help.