Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

python - How to to iterate through a specific time range in a logfile?

For example: [2017-04-14 03:56:22,085109]

If this is the time where event A happens, I want to go 15 minutes before this line in the logfile which will have thousands of line and I want to iterate through everyline in that period and look for specific keywords. Every line in the logfile has the time stamp with the same format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can filter the desired lines with a start and end time.

main.py

from datetime import datetime, timedelta

event_time = datetime.strptime('2017-04-14 03:56:22,085109', '%Y-%m-%d %X,%f')
event_start = event_time - timedelta(minutes=15)


def line_date(line):
    return datetime.strptime(line[1:27], '%Y-%m-%d %X,%f')


with open('example.log', 'r') as myfile:
    lines = filter(lambda x: event_start <= line_date(x) <= event_time,
                   myfile.readlines())


print(lines)

example.log

[2017-04-13 03:56:22,085109] My old log
[2017-04-14 03:55:22,085109] My log in less than 15 minutes ago
[2017-04-14 03:56:22,085109] My important event
[2017-04-14 03:57:22,085109] Log after my important event

But I recommend you to use python3 (instead of python2). filter returns an iterator, instead of the full list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...