很多類似於日志這樣的文件中都有時間字段。有時候,我們希望取出某一段時間段的數據。例如這個文件:
[root@www py2]# cat mylog.log 2019-05-15 08:10:01 aaaa 2019-05-15 08:32:00 bbbb 2019-05-15 09:01:02 cccc 2019-05-15 09:28:23 dddd 2019-05-15 10:42:58 eeee 2019-05-15 11:08:00 ffff 2019-05-15 12:35:03 gggg 2019-05-15 13:13:24 hhhh
我們想要得到9:00到12:00之間的數據。觀察文件,發現其特點是前19個字符是時間,只要將這部分數據轉換成相應的時間對象,判斷它是否介於9:00到12:00之間即可:
## 使用time模塊
import time logfile = 'mylog.log' # 取出日志文件的每一行,判斷時間,如果是9點到12點之間的,則打印 t9 = time.strptime('2019-05-15 09:00:00', '%Y-%m-%d %H:%M:%S') t12 = time.strptime('2019-05-15 12:00:00', '%Y-%m-%d %H:%M:%S') with open(logfile,'r') as fobj: for line in fobj: t = time.strptime(line[:19], '%Y-%m-%d %H:%M:%S') if t > t12: # 當時間直接大於最大時間時,則直接退出,程序執行的更快 break if t > t9: print(line,end='')
## 使用datetime模塊
from datetime import datetime logfile = 'mylog.log' start = datetime.strptime('2019-05-15 09:00:00', '%Y-%m-%d %H:%M:%S') end = datetime.strptime('2019-05-15 12:00:00', '%Y-%m-%d %H:%M:%S') with open(logfile,'r') as fobj: for line in fobj: t = datetime.strptime(line[:19], '%Y-%m-%d %H:%M:%S') if t > end: break if t > start: print(line,end='')