Reputation: 11
I'm fairly new to programming and have a puzzler on my hands. Using Python code I'm trying to search a text file that has a timestamp that is a string along with another data value. I'm trying to give my search a limit of + or - 3 minutes so that the timestamp that is being searched for will use the closest timestamp in the text file and return the data value associated with the timestamp.
Here is an example of the text file that is being searched:
2014/05/01 00:00 -0.075
2014/05/01 00:06 -0.056
2014/05/01 00:12 -0.037
2014/05/01 00:18 -0.017
2014/05/01 00:24 0.002
2014/05/01 00:30 0.021
2014/05/01 00:36 0.040
2014/05/01 00:42 0.061
2014/05/01 00:48 0.081
2014/05/01 00:54 0.102
2014/05/01 01:00 0.124
2014/05/01 01:06 0.146
2014/05/01 01:12 0.168
The bit of code that I have written thus far is:
with open(TEXTFILE,'r') as searchfile:
for line in searchfile:
x = line.split(' ',2)
if DateVariable == x[0]:
if TimeVariable == x[1]:
print x[2]
break
else:
print 'No timestamp match was found.'
This bit of code works but for only when searching for a timestamp that is an exact match to the user input. I'm not sure how to tackle a + or - 3 minute limit search. Thank you in advance!
Upvotes: 1
Views: 455
Reputation: 62369
You could try something like this, assuming that your TimeVariable
is also in the same format, which seems a reasonable assumption:
TimeFields = TimeVariable.split(':')
TimeInMinutes = int(TimeFields[0]) * 60 + int(TimeFields[1])
with open(TEXTFILE,'r') as searchfile:
for line in searchfile:
x = line.split(' ',2)
if DateVariable == x[0]:
TestFields = x[1].split(':')
EntryTime = int(TestFields[0]) * 60 + int(TestFields[1])
TimeDelta = EntryTime - TimeInMinutes
if -3 <= TimeDelta <= 3:
print x[2]
break
else:
print 'No timestamp match was found.'
There's a little extra logic you'll need to add for the 6 minutes around midnight (or around noon, for that matter, if those are 12-hour times), but that shouldn't be too hard to add in...
Upvotes: 1