Here I want to calculate time interval in between row by row in time column import from csv file. my start time 6.00 a.m and my end time is next day 6.00 a.m. In between this time periods how to find time interval period. Can anyone help me to solve this problem? Here I upload my code and csv file.

def time_diff(start, end):
start.append(pd.to_datetime(data['time'][0],formt = '%H:%M:%S').time())
end.append(pd.to_datetime(len(data['time']), format='%H:%M:%S').time())
if isinstance(start, datetime_time): # convert to datetime
    assert isinstance(end, datetime_time)
    start, end = [datetime.combine(datetime.min,i) for t in [start, end]]
if start <= end: 
    return end - start
else: # end < start 
    end += timedelta(1) # +day
    assert end > start
    return end - start
for time_range in range (len(data['time'])):
start = [datetime.strptime(t,'%H:%M:%S') for t in time_range]
end = [datetime.strptime(t,'%H:%M:%S') for t in time_range]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())

my csv file :-

enter image description here

I got an error:-

TypeError                                 Traceback (most recent call last)
 <ipython-input-28-be40ae41d284> in <module>()
 12         return end - start
 13 for time_range in range (len(data['time'])):
 ---> 14     start = [datetime.strptime(t,'%H:%M:%S') for t in time_range]
 15     end = [datetime.strptime(t,'%H:%M:%S') for t in time_range]
 16     print(time_diff(s, e))

 TypeError: 'int' object is not iterable
  • $\begingroup$ is there any specific reason that you have used pandas for this problem? $\endgroup$ Dec 5 '18 at 3:37
for time_range in range (len(data['time'])):
start = [datetime.strptime(t,'%H:%M:%S') for t in time_range]

time_range is an integer due to using range(int). There is nothing to iterate using an int. It is not a container.

  • $\begingroup$ If I want to calculate the difference in between time ,in this whole column row by row ,then what I have to cahnge in my code? $\endgroup$
    – user59020
    Dec 4 '18 at 8:14
  • $\begingroup$ Iterate through the rows and take the difference. $\endgroup$ Dec 4 '18 at 8:44
  • $\begingroup$ Can you suggest me some solutions to solve it. I didn't have any idea to do that row. I wrote but I don't know how to combine that two codes. data['time'] = [] for i, row in enumerate(rows): data['time'].append([row]) try: for next_row in rows[i + 1:]: if abs(row['time'] - next_row['time']) < timedelta(): df[i].append(next_row) else: break except IndexError: continue $\endgroup$
    – user59020
    Dec 4 '18 at 8:54
  • $\begingroup$ I guess you can't iterate over dataframe. have you considered here? $\endgroup$ Dec 4 '18 at 9:15
  • $\begingroup$ yes I looked that article.but still I didn't get better solution to solve this error? $\endgroup$
    – user59020
    Dec 4 '18 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy