У меня есть текстовый файл a.txt, и я хочу получить все строки за последние 48 часов с даты earlier
- 20190322 сохранил его в текстовом файле.
a.txt
Mon Sep 17 04:00:05 2018 abc.pl:16199: snononsonfvnosnovoosr
Mon Sep 17 04:00:05 2018 abc.pl:16199: ahelooa afoaona woom
Fri Jan 18 04:00:05 2019 abc.pl:16199: qojfcmqcacaeia
Sat Jan 19 04:00:05 2019 abc.pl:16199: user: number is 93823004
user: number is 93823004
Sun Feb 17 04:00:05 2019 abc.pl:16199: user 7fb31ecfa700
Mon Feb 18 04:00:05 2019 abc.pl:16199: Exit Status = 0x0
Tue Feb 19 04:00:05 2019 abc.pl:16199: std:ZMD:
Mon Mar 18 04:00:05 2019 abc.pl:16199: snononsonfvnosnovoosr
Tue Mar 19 04:00:05 2019 abc.pl:16199: ahelooa afoaona woom
Wed Mar 20 04:00:05 2019 abc.pl:16199: qojfcmqcacaeia
Thu Mar 21 04:00:05 2019 abc.pl:16199: ahelooa afoaona woom
"udijandoa:nqHmsdddKN0WczMbHxK8Th+azfs=,domain=Device" -H
"jfnkoankfn" -H "auidiuayhca" -H "pakfpapf" -H "manfonancnana" -H
"pklamfkcm" --verbose --afpampkmfca-alkdkap
Tue Mar 22 04:01:59 2019 abc.pl:24549: $vca= {
'rc' => '',
'rco' => '4542',
};
Fri Mar 23 04:00:05 2019 abc.pl:16199: qojfcmqcacaeia
earlier_date = '20190322'
Ожидаемый результат :
result.txt:
Wed Mar 20 04:00:05 2019 abc.pl:16199: qojfcmqcacaeia
Thu Mar 21 04:00:05 2019 abc.pl:16199: ahelooa afoaona woom
"udijandoa:nqHmsdddKN0WczMbHxK8Th+azfs=,domain=Device" -H
"jfnkoankfn" -H "auidiuayhca" -H "pakfpapf" -H "manfonancnana" -H
"pklamfkcm" --verbose --afpampkmfca-alkdkap
Tue Mar 22 04:01:59 2019 abc.pl:24549: $vca= {
'rc' => '',
'rco' => '4542',
};
Мое решение:
from datetime import datetime, timedelta
earlier_date = '20190322'
earlier_date = datetime.strptime(earlier_date, '%Y%m%d').strftime("%b %d %H:%M:%S %Y")
cut_date = datetime.strptime(earlier_date, "%b %d %H:%M:%S %Y") - timedelta(hours=48)
print(cut_date)
output = open('result.txt', 'w', encoding='utf-8')
def parse_file(lines_all):
for l in lines_all:
index = l.find(' ')
if index > -1:
yield l[index + 1:24], l
else:
pass
with open('a.txt', 'r') as f:
lines = parse_file(f)
dates, line = next(lines)
print(dates)
for dates, line in lines:
dates = datetime.strptime(dates, "%b %d %H:%M:%S %Y")
if cut_date <= dates:
print(dates)
output.write(line)
Проблема : Невозможно сравнить даты. Таким образом, ничего не записывает в текстовый файл.