Sunday, September 25, 2022

Python code to find the time difference between all occurrences of a pair of events in a log file

from datetime import datetime
import re

def parse_file(filename, expression1, expression2):
    lines = tuple(open(filename, 'r'))
    expression1Found = False
    expression2Found = False
    pattern = '(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9].[0-9][0-9][0-9]'

    for line in lines:
        if expression1 in line:
            timeString1 = re.search(pattern, line).group()
            expression1Found = True
        if expression2 in line:
            timeString2 = re.search(pattern, line).group()
            expression2Found = True

        if expression1Found and expression2Found:
            timePattern = '%m-%d %H:%M:%S.%f'
            epoch = datetime(1970, 1, 1)
            time1 = (datetime.strptime(timeString1, timePattern) - epoch)
            time2 = (datetime.strptime(timeString2, timePattern) - epoch)
            if int((time2 - time1).total_seconds() * 1000) > 1:
                print(int((time2 - time1).total_seconds() * 1000))

            # Reset and start searching for the next pair of occurrences of expression1 and expression2
            expression1Found = False
            expression2Found = False

if __name__ == "__main__":
    parse_file('filepath', 'even1', 'event2')

No comments:

Post a Comment