【问题标题】:Is there a way to print data from a log file between two endpoints in python有没有办法从python中两个端点之间的日志文件中打印数据
【发布时间】:2020-07-13 08:00:12
【问题描述】:

我有一个日志文件,正在尝试打印两个日期之间的数据。

2020-01-31T20:12:38.1234Z, asdasdasdasdasdasd,...\n
2020-01-31T20:12:39.1234Z, abcdef,...\n
2020-01-31T20:12:40.1234Z, ghikjl,...\n
2020-01-31T20:12:41.1234Z, mnopqrstuv,...\n
2020-01-31T20:12:42.1234Z, wxyzdsasad,...\n

这是示例日志文件,我想打印 2020-01-31T20:12:39 到 2020-01-31T20:12:41 之间的行。

到目前为止,我已经找到并打印了起始日期线。我已经过了开始日期作为开始。

with open("logfile.log") as myFile:
    for line in myFile:
        linenum += 1
        if line.find(start) != -1:
            print("Line " + str(linenum) + ": " + line.rstrip('\n'))

但是我怎样才能一直打印到结束日期?

【问题讨论】:

标签: python python-3.x file-handling


【解决方案1】:

不是 python 中的答案,而是 bash 中的答案。

sed -n '/2020-01-31T20:12:38.1234Z/,/2020-01-31T20:12:41.1234Z/p' file.log

输出:

2020-01-31T20:12:38.1234Z, asdasdasdasdasdasd,...\n
2020-01-31T20:12:39.1234Z, abcdef,...\n
2020-01-31T20:12:40.1234Z, ghikjl,...\n
2020-01-31T20:12:41.1234Z, mnopqrstuv,...\n

【讨论】:

  • 非常感谢,但我需要在 python/java 中执行此操作
  • 一个肮脏的hack是通过os.system调用从python文件调用bash函数
【解决方案2】:

由于时间字符串已经在您的文件中结构良好,您可以在您感兴趣的时间之间进行简单的字符串比较,而无需将字符串转换为日期时间对象。

使用csv模块读取文件,使用默认的逗号分隔符,然后使用filter()函数在两个日期之间进行过滤。

import csv

reader = csv.reader(open("logfile.log"))
filtered = filter(lambda p: p[0].split('.')[0] >= '2020-01-31T20:12:39' and p[0].split('.')[0] <= '2020-01-31T20:12:41', reader)
for l in filtered:
    print(','.join(l))

编辑: 我使用split() 来删除字符串比较中时间字符串的小数部分,因为您对时间感兴趣到最接近的分钟精度,例如2020-01-31T20:12:39。

【讨论】:

  • 有没有办法像删除方括号的普通行一样格式化输出
  • @NiKK 是的。通过这样做:print(','.join(l))。已更新。
  • 使用 rpartition 没有输出。但是,如果我只使用 p[0].partition 那么我可以获得正确的输出。主要问题是没有打印最后一行。结果列表仅打印到倒数第二行。不打印日志日期为“2020-01-31T20:12:41”的行
  • @NiKK 我已将rpartition 更改为split。这应该使日期字符串达到 first 点。这应该适用于您在问题中提供的示例数据。不知道你的真实数据是不是不一样?确保使用 >= 和
【解决方案3】:

如果你想在 python 中,

import time  
from datetime import datetime as dt  

def to_timestamp(date,forma='%Y-%m-%dT%H:%M:%S'):  
    return time.mktime(dt.strptime(date,forma).timetuple()) 

start=to_timestamp(startdate)
end=to_timestamp(enddate)
logs={}
with open("logfile.log") as f:
    for line in f:
        date=line.split(', ')[0].split('.')[0]
        logline=line.split(', ')[1].strip('\n')
        if to_timestamp(date)>=start and to_timestamp(end) <= end:
            logs[date]=logline

【讨论】:

  • 上面的代码给了我一个错误 TypeError: strptime() argument 1 must be str, not datetime.datetime。我也在尝试打印日志行,同时阅读它们
  • 刚刚过去的日期作为文件中的字符串,例如“2020-01-31T20:12:38”,只需执行print(f'{date}\t{logline}')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多