Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem on for-if loop
#1
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,
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  while loop problem fid 2 2,246 Jun-19-2020, 07:21 PM
Last Post: fid
  for loop problem with opencv Miradox 1 2,416 Dec-23-2018, 10:39 PM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020