我有一個日誌文件,在.txt格式閱讀日誌文件,並找到具體細節
現在我必須找到特定時間框架之間使用Python的日誌條目。
我嘗試使用迭代和範圍。
所以請接受任何建議。
日誌文件看起來像這樣:
2015年12月15日00:51:01904信息restserver.py 113 v ................. .......等等
所以只能在一定的時間範圍內找到日誌條目。
我有一個日誌文件,在.txt格式閱讀日誌文件,並找到具體細節
現在我必須找到特定時間框架之間使用Python的日誌條目。
我嘗試使用迭代和範圍。
所以請接受任何建議。
日誌文件看起來像這樣:
2015年12月15日00:51:01904信息restserver.py 113 v ................. .......等等
所以只能在一定的時間範圍內找到日誌條目。
如果你讀了你的整個日誌文件轉換爲一個字符串,那麼你可以使用這個:
import re
str = '2015-12-15 00:51:01,904 INFO restserver.py 113 .... 2015-12-16 00:51:01,904 INFO restserver.py 114 ....'
date1="2015-12-15 00:51:01"
date2="2015-12-16 00:51:01"
result = re.search(date1+'(.*)'+date2, str)
print result.group(1)
輸出:,904信息restserver.py 113 ....
使用情況下(由OP)編輯代碼:
#!/usr/bin/env python
#Import the regular expression
import re
#Set the begining time and name it as starttime
starttime="03:00:00"
#Set the ending time and name it as endtime
endtime="03:59:59"
#Specify the time format
time_re = re.compile(r'(\d+:\d+:\d+)')
#Using the condition with open("abc.log", "r") as fh:
for line in fh.readlines():
match = time_re.search(line)
if match:
matchDate = match.group(1)
if matchDate >= starttime and matchDate <= endtime:
print match.string.strip()
感謝Ani Menon:我終於明白了:代碼如下:#!/ usr/bin/env python #導入正則表達式 import re #設置開始時間並將其命名爲starttime starttime =「03: 00:00「 #設置結束時間並將其命名爲endtime endtime =」03:59:59「 #指定時間格式 time_re = re.compile(r'(\ d +:\ d +:\ d +) 「) #使用條件 張開( 「abc.log」, 「R」)作爲FH:在fh.readlines()爲線 : 匹配= time_re.search(線) 如果匹配: matchDate = match.group(1) if matchDate> = starttime和matchDate <= endtime: print match.string.strip() –
進口重新
打印 「任務從」
打印 「的開始時間爲03:00:00」
starttime =「03:00:00」
打印「的結束時間是3點59分59秒」
ENDTIME =「3點59分59秒」
time_re = re.compile(R '(\ d +:\ d +:\ d +)')
張開( 「abc.log」, 「R」)作爲FH:
for line in fh.readlines():
match = time_re.search(line)
if match:
matchDate = match.group(1)
if matchDate >= starttime and matchDate <= endtime:
print match.string.strip()
打印「任務完成」
後,你做了&也txt文件的數據的代碼片斷。 –
您的問題不清楚,因爲我們不知道您的數據的格式。請提供樣本輸入以及您的請求輸出在這種情況下的樣子。 –
仍然缺乏細節。如何增加一些額外的樣本行並向我們展示如何使用時間框架進行搜索?至少在一種情況下顯示預期的結果。 –