126-取出指定时间段的文本

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

[root@myvm untitled]# cat myfile.txt 
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之间即可:

[root@myvm untitled]# cat cut_file.py 
import time

fname = 'myfile.txt'
t9 = time.strptime('2019-5-15 09:00:00', '%Y-%m-%d %H:%M:%S')
t12 = time.strptime('2019-5-15 12:00:00', '%Y-%m-%d %H:%M:%S')

with open(fname) as fobj:
    for line in fobj:
        t = time.strptime(line[:19], '%Y-%m-%d %H:%M:%S')
        if t9 < t < t12:
            print(line, end='')

这是我们很容易直接想到的,但是如果文件有上万行,满足条件的时间只出现在前100行以内呢?按上面的写法,文件中所有的行都要遍历一遍,这完全没有必要。如果在不满足条件时,及时将循环中断,可以大大地提升程序的运行效率。所以,更好的写法如下:

[root@myvm untitled]# cat cut_file.py 
import time

fname = 'myfile.txt'
t9 = time.strptime('2019-5-15 09:00:00', '%Y-%m-%d %H:%M:%S')
t12 = time.strptime('2019-5-15 12:00:00', '%Y-%m-%d %H:%M:%S')

with open(fname) 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='')

[root@myvm untitled]# python3 cut_file.py 
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

你可能感兴趣的:(126-取出指定时间段的文本)