我有一个日志文件,正在尝试打印两个日期之间的数据
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'))
但是我怎么能一直打印到截止日期呢
由于时间字符串在文件中的结构已经很好,您只需在感兴趣的时间之间进行简单的字符串比较,而无需将字符串转换为datetime对象
使用
csv
模块读取文件,使用默认的逗号分隔符,然后使用filter()
函数在两个日期之间进行筛选编辑: 我使用
split()
删除字符串比较中时间字符串的小数部分,因为您对精确到最接近分钟的时间感兴趣,例如2020-01-31T20:12:39如果您想使用python
答案不是python,而是bash
sed -n '/2020-01-31T20:12:38.1234Z/,/2020-01-31T20:12:41.1234Z/p' file.log
输出:
相关问题 更多 >
编程相关推荐