[Tutor] How to print lines within two timestamp

Alan Gauld alan.gauld at yahoo.co.uk
Sat Oct 27 04:33:10 EDT 2018

On 27/10/2018 08:02, Asad wrote:

>>> string = f3.read ()
>>> regex = re.compile ( "\n" )
>>> st = regex.sub ( " ", string )
>> I suspect regular string methods would be simpler here.
>> answer : can you please provide the code to replace above

st = string.replace("\n"," ")

>>> if re.search ('ERR-1:', st ):
>>>     x = re.findall ( "(\w{3})\s+([0-9]{2})\s+(\d+):(\d+):(\d+)\s+(\d+)",
>> st )
>>>     j = x[0][0] + " "+ x[0][1]+" " + x[0][2] +":"+ x[0][3]+":" +
>>> x[0][4]+" " + x[0][5]
>>>     h = x[1][0] + " "+ x[1][1]+" "+ x[1][2] +":" + x[1][3] +":"+
>>> x[1][4] +" "+ x[1][5]
>> I'm not sure what exactly this is doing, but I suspect
>> datetime.strftime might do it better.
>> Answer: Its extracting all the dates in the format :Oct 22 10:21:15 2018

Sorry, I saw the re.search but missed the findall().
My bad.

>> Can you show us the full output? It should start with your header line?
>    This is the complete output

Again my bad. I thought you had a single line header,
but that must have been another post, oops!

>    My requirement is to start(y) and end timestamp (k) from logA.txt which
> the code is getting now correctly then open logC11.txt see the timestamp
> nearest to start(y) which its doing now
> 2018-10-22 10:21:23  and then look for errors(ERR-2 and ERR-3) in the lines
> in logC11.txt starting from  2018-10-22 10:21:23 and before the timestamp
> (k) ==> here i need help my code is searching for ERR-2 and ERR-3 occurance
> in logC11.txt anywhere in the file I want it to search in a specific window
> of  2018-10-22 10:21:23 and less than timestamp (k)

The traditional way to do this is to use a sentinel variable.
That is you scan the lines until you reach your start condition
and set the variable to True.
You then process all the lines until your end condition
where you set the sentinel to false (or exit the loop).

During your processing you only proceed to analyses the lines if the
sentinel is True.

In pseudo code:

start,end = find_times("logA.txt")

for line in open("logC11.txt"):
    if start in line: found = True
    if end in line: break
    if found:

Obviously with time values its a little bit more complex
than a simple 'in' test but you get the idea I hope.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list