python将输出行保存到新文件中

时间:2012-09-11 03:22:08

标签: python

我想对日志文件使用python create filter。获得最近7天的记录。 但是当我不知道如何比较时间。 比如当前时间是11/9/2012,我想从2012年9月9日到现在

获取记录

日志文件,如

 Sat Sep  2 03:32:13 2012 [pid 12461] CONNECT: Client "66.249.68.236"
 Sat Sep  2 03:32:13 2012 [pid 12460] [ftp] OK LOGIN: Client "66.249.68.236", anon     password "gxxglxxxxt@google.com"
 Sat Sep  2 03:32:14 2012 [pid 12462] [ftp] OK DOWNLOAD: Client "66.249.68.236",   "/pub/10.5524/100001_101000/100022/readme.txt", 451

我使用这个

  def OnlyRecent(line):
       print time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y")
       print time.time()
    if  time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y") < time.time():
        return True
    return False

但它显示

   (2012, 9, 2, 3, 32, 13, 5, 246, -1) 
    1347332968.08
   (2012, 9, 2, 3, 32, 13, 5, 246, -1)
    1347332968.08
   (2012, 9, 2, 3, 32, 14, 5, 246, -1)
    1347332968.08

选择多行之后,如何创建新文件(* .txt或log)来存储脚本中的文件,文件名使用当前日期

由于

3 个答案:

答案 0 :(得分:1)

您可以使用time.mktime将时间元组转换为unix时间戳。

>>> import time
>>> time.mktime((2012, 9, 2, 3, 32, 13, 5, 246, -1))
1346527933.0

答案 1 :(得分:1)

使用datetime.datetime.strptime和datetime.datetime.now()来使用相同的数据结构:

from datetime import datetime 
def OnlyRecent(line):
  return  datetime.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y") < datetime.now()

答案 2 :(得分:1)

而不是time使用datetimetimedelta

seven_days = datetime.timedelta(days=7)

def OnlyRecent(line):
    dt = datetime.datetime.strptime(line.split('[')[0].strip(), "%a %b %d %H:%M:%S %Y")
    return dt > datetime.datetime.now() - seven_days