python百例 --- 取出指定时间段的文本

很多类似于日志这样的文件中都有时间字段。有时候,我们希望取出某一段时间段的数据。例如这个文件:

[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='')

猜你喜欢

转载自www.cnblogs.com/liangbc/p/12690965.html