在python中按日期范围过滤日志的最佳方法 [英] The best way to filter a log by a dates range in python

查看:511
本文介绍了在python中按日期范围过滤日志的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打印与日期时间范围匹配的日志行的最佳方法是什么? 例如:

What's the best way to print log lines that match a datetime range. For example:

我只想打印带日期的行 从:2012/09/30-00:00:10 到:2012/09/30-00:00:13

I would like to print only lines with dates from: 2012/09/30-00:00:10 to: 2012/09/30-00:00:13

2012/09/30-00:00:08.773 log error
2012/09/30-00:00:09.034 log warning
2012/09/30-00:00:09.352 log info
2012/09/30-00:00:10.526 log info
2012/09/30-00:00:10.995 log warning
2012/09/30-00:00:12.014 log warning
2012/09/30-00:00:18.035 log error
2012/09/30-00:00:21.733 log fatal
2012/09/30-00:00:21.981 log info

它应该打印:

2012/09/30-00:00:10.526 log line
2012/09/30-00:00:10.995 log line
2012/09/30-00:00:12.014 log line

由于要使用生产服务器,因此我想以一种经济高效的方式进行此操作.请只使用Python. 谢谢!

I would like to do this in a cost-effective way, as I'm using production servers. Python only please. Thanks!

推荐答案

Actullay,日志格式允许比较日期字符串而不将其转换为datetime.

Actullay, the log format allows to compare date strings without their conversion to datetime.

with open('mylog.log','r') as f:
    for line in f:
        d = line.split(" ",1)[0] 
        if d >= '2012/09/30-00:00:10' and d <= '2012/09/30-00:00:13':
            print line

这篇关于在python中按日期范围过滤日志的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆