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

前端 未结 5 1084
佛祖请我去吃肉
佛祖请我去吃肉 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:18

    As per Tim's assumption you're reading a log file, line by line, then use itertools.

    from itertools import dropwhile, takewhile
    
    from_dt, to_td = '2012/09/30-00:00:10', '2012/09/30-00:00:13'
    with open('logfile') as fin:
        of_interest = takewhile(lambda L: L <= to_td, dropwhile(lambda L: L < from_dt, fin))
        for line in of_interest:
            print line
    

提交回复
热议问题