Many files like logs have a time field. Sometimes, we want to retrieve data for a certain period of time. For example this file:
[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
We want to get the data between 9:00 and 12:00. Observe the file and find that its characteristic is that the first 19 characters are time, as long as this part of the data is converted into the corresponding time object, and it is judged whether it is between 9:00 and 12:00:
## Using the time module
Import Time logfile = ' mylog.log ' # Each line fetch log file, determination time, if it is between 9:00 to 12:00, the print T9 = the 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: # , when time is greater than the maximum time directly, directly exit the program executed faster BREAK IF T> T9: Print (Line, End = ' ' )
## Use datetime module
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='')