Reputation: 1587
i want to using python create filter for a log file. get recent 7 days record. but when i didn't know how to compare time. like current time is 11/9/2012, i want to get records from 04/9/2012 to now
the log file like
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 "[email protected]"
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
i using this one
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
But it shows
(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
after select many lines, how can i create new file(*.txt or log) to store those in script, the file name use current date
Thanks
Upvotes: 0
Views: 209
Reputation: 308520
Instead of time
use datetime
and timedelta
.
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
Upvotes: 1
Reputation: 501
Use datetime.datetime.strptime and datetime.datetime.now() to use the same data structure:
from datetime import datetime
def OnlyRecent(line):
return datetime.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y") < datetime.now()
Upvotes: 1
Reputation: 441
you can use time.mktime to convert a time tuple to unix timestamp .
>>> import time
>>> time.mktime((2012, 9, 2, 3, 32, 13, 5, 246, -1))
1346527933.0
Upvotes: 1