在python中,有没有一种方法可以从两个端点之间的日志文件打印数据

2024-10-05 19:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'))

但是我怎么能一直打印到截止日期呢


Tags: 文件数据示例withlineopenmyfilelogfile
3条回答

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

使用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

如果您想使用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

答案不是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

相关问题 更多 >