【问题标题】:How to to iterate through a specific time range in a logfile?如何遍历日志文件中的特定时间范围?
【发布时间】:2017-10-31 13:30:52
【问题描述】:

例如: [2017-04-14 03:56:22,085109]

如果这是事件 A 发生的时间,我想在日志文件中的这一行之前 15 分钟,这将有数千行,我想遍历该期间的每一行并查找特定的关键字。日志文件中的每一行都有相同格式的时间戳。

【问题讨论】:

  • 看看datetime
  • 我强烈建议您使用一些数据库来运行这种类型的分析,而不是在 python 中这样做。
  • 可以使用datetime.strptime()类方法将文件中的时间转换成Python的datetime实例,支持比较。然后,您可以使用它们来选择文件中感兴趣的时间间隔内的行(假设您在 datetime 实例中也有事件 A 的时间)。

标签: python python-2.7 datetime logfile-analysis


【解决方案1】:

您可以使用开始和结束时间过滤所需的行。

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

但我建议您使用 python3(而不是 python2)。 filter 返回一个迭代器,而不是完整列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2020-02-14
    • 2020-12-14
    • 2011-05-30
    相关资源
    最近更新 更多