這是代碼:在Python 2.7,如何提取和打印日期,時間,以及更
#!/usr/bin/env python
#Import the datetime
from datetime import datetime
import re
#Create two datetime object for limit 1 and limit 2 as dt1 and dt2 respectively
dt1 = datetime.strptime("01:00:00","%H:%M:%S").time()
dt2 = datetime.strptime("04:59:59","%H:%M:%S").time()
#Create a compiler for regular expression
init_re = re.compile(r'(INIT)')
time_re = re.compile(r'(\d+:\d+:\d+)')
# read line from test.log file
for line in open("test.log", "r"):
match = time_re.search(line) #Search time format for each line
if match:
matchtime = match.group(1)
dt_match = datetime.strptime(matchtime, '%H:%M:%S').time()
#Time formmat match
if dt_match >= dt1 and dt_match <= dt2:
match1 = init_re.search(line) #search INIT format
if match1:
matchinit = match1.group(0)
print match.string.strip()
下面是日誌文件的一部分的區域:
2015-12-15 00:51:01,904 INFO restser.py 113 [INIT] [netkv_restser: peek] [req_id: f0aa7ab5-6192-4231-93cd-82a53936a072] [request: {u'key_space': u'martech_user_index', u'table_name': u'nettopic', u'key': 9569}]
我想輸出像這樣:
[Date: ] [Time: ] [INIT] [netkv_restser: ] [req_id: ]
實施例:
[Date:2015-12-15 ] [Time:00:51:01,904 ] [INIT] [netkv_restser:peek ] [req_id:f0aa7ab5-6192-4231-93cd-82a53936a072 ]
注意:如果您足夠好地編輯代碼,請提供足夠的解決方案。我不想聽起來粗魯,但它讓我感到厭煩。
注意:我正在使用Python 2.7.6。
爲什麼你問[一個問題(http://stackoverflow.com/questions/36975197/how-to-extract-specific-data-from-a-string )多次? – EbraHim
我想要幫助而沒有人提供它,所以我重建了我的代碼並再次提問。Buddy,Help out no。 –
問兩次對你沒有任何幫助,根據SO規則是不合法的。不想聽起來很粗魯,但我編輯了你最後一個問題,並留下了一個答案。 – EbraHim