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

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

    I am not sure of the performance implications (I suspect Tim's answer might be faster), but this approach works for any date range:

    >>> def dates(start,end):
    ...     for i in range(int((end-start).seconds)):
    ...         yield start + datetime.timedelta(seconds=i)
    ...
    >>> fmt = '%Y/%m/%d-%H:%M:%S'
    >>> from_date = datetime.datetime.strptime('2012/09/30-00:00:10',fmt)
    >>> till_date = datetime.datetime.strptime('2012/09/30-00:00:13',fmt)
    >>> with open('file.log') as f:
    ...     for line in f:
    ...         if datetime.datetime.strptime(line.split()[0][:-4],fmt) in dates(fro
    m_date,till_date):
    ...              print line
    ...
    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
    

提交回复
热议问题