Python Forum

Full Version: problem on for-if loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I want to test the detection of an event using the input time t of data in a file:
if the difference between t[i+1] and t[i] is inferior to 2 minutes more than once (ie: t[i+1]-t[i]=1 min, t[i+2]-t[i+1]=1, etc.), the event is detected at time t[i], else there is no event and we proceed to the next interval.

The file tested looks like this:
06-MAR-2018 00:01, 100
06-MAR-2018 00:06, 105
06-MAR-2018 00:11, 102
06-MAR-2018 00:15, 90
06-MAR-2018 00:18, 300
06-MAR-2018 00:19, 325
06-MAR-2018 00:20, 250
06-MAR-2018 00:23, 150
etc.

(there is a file per day, and each day can contain multiple events)

I made this:
import numpy as np
imprt csv
import datetime as dt

Date=[]
data=[]
with open('signal.dat') as f:
 signal=csv.reader(f,delimiter=',')
 for row in signal :
  Date.append(str(row[0]))
  data.append(int(row[1]))

t = [dt.datetime.strptime(x,'%d-%b-%Y %H:%M) for x in Date]

for i in range(len(t)-1)):
 D= [t[i+1]-t[i]]
 if D<120: #time difference between t[i+1] and t[i] is strictly inferior to 120 seconds
  break
 print("event at:", t[i]) 
The program works (I do not have any error message), but the output doesn't match what I thought I asked :
Output:
('event at:',datetime.datetime(2018, 3, 6, 0, 1)) ('event at:',datetime.datetime(2018, 3, 6, 0, 6)) ('event at:',datetime.datetime(2018, 3, 6, 0, 11)) ('event at:',datetime.datetime(2018, 3, 6, 0, 15)) ('event at:',datetime.datetime(2018, 3, 6, 0, 18)) ('event at:',datetime.datetime(2018, 3, 6, 0, 19)) ... ('event at:',datetime.datetime(2018, 3, 6, 0, 23)) etc.
In other words, all times are in the output, while I only want ('event at:', datetime.datetime(2018, 3, 6, 0, 18)) in this output.

I tried printing the output in the "if" block, before/after the "break", and in both cases there is no output and no error message either.
I initially tried to use "dt.timedelta(0, 120)" instead of 120, but I had the output error "TypeError: can't compare datetime.timedelta to list" as D is the list "[datetime.timedelta(0, 300), datetime.timedelta(0, 300), datetime.timedelta(0, 240), datetime.timedelta(0, 180), datetime.timedelta(0, 60),etc.]"

I am completely lost on where I got it wrong...
Does anyone have an idea of an alternate way of doing this (it is kind of urgent, I need this to set an alarm during a crisis/event that could happen anytime)?

Thanks in advance,
Try D = (t[i+1] - t[i]).total_seconds() at line 16. Also 'print' needs to be in the 'if' before 'break'.

Use a python tutorial, [] and () are not interchangeable.