The best way to filter a log by a dates range in python

前端 未结 5 1116
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 19:51

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

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

5条回答
  •  旧巷少年郎
    2021-01-13 20:12

    .startswith() example:

    prefixes = tuple("2012/09/30-00:00:1%d" % i for i in range(3))
    with open('mylog.log', 'rb') as file:
        print ''.join(line for line in file if line.startswith(prefixes)),
    

    You could optimize it by using a single static prefix and then testing preselected lines using a regex or datetime objects later.

    If the lines are sorted by date in the input; you could break earlier without reading the whole file.

提交回复
热议问题