利用python提取某段时间范围的日志信息

1)strptime()函数使用

  • strptime():根据格式的时间字符串,返回值是一个struct_time所返回gmtime()或localtime()
使用语法:

time.strptime(string[,format])

  • string:时间内容
  • format:时间格式
>>> print(time.strptime("2022-02-22","%Y-%m-%d"))
time.struct_time(tm_year=2022, tm_mon=2, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=53, tm_isdst=-1)

2)字符串分割或截取

split()函数的使用
  • split():通过指定分隔符对字符串进行拆分,并返回分割后的字符串列表

(PS:re模块的group也可以对字符串进行分割。)

使用语法:

split(‘分隔符’,分隔次数)[选取分片的下标]

  • 默认分隔符是空格
  • 分片选取中,0和正数是从左到右,负数是指从右到左。
>>> str = '123|aa|ww|ccm'

>>> print(str.split('|'))
['123', 'aa', 'ww', 'ccm']

>>> print(str.split('|',2))
['123', 'aa', 'ww|ccm']

>>> print(str.split('|',2)[-1])
ww|ccm
mylog.log
2022-02-10 02:02:58.000000+00|zhangsan|jdbc|172.16.0.104|active|select * from table1;
2022-02-10 04:01:30.000000+00|zhangsan|jdbc|172.16.0.104|active|select * from table2;
2022-02-10 04:30:19.000000+00|zhangsan|jdbc|172.16.0.104|active|select * from table3;
2022-02-10 04:30:19.000000+00|zhangsan|jdbc|172.16.0.104|active|select * from table;
2022-02-10 04:30:19.000000+00|zhangsan|jdbc|172.16.0.104|active|select * from table;
py测试
# -*- coding: UTF-8 -*-

import time

# 日志文件名称
logfile = 'mylog.log'

def choose_log1():
    # 定义截取的时间范围
    start_time = time.strptime('2022-02-10 04:30:00','%Y-%m-%d %H:%M:%S')
    end_time = time.strptime('2022-02-19 05:10:00','%Y-%m-%d %H:%M:%S')
    
    # 打开日志
    with open(logfile,'r') as logs:
        for line in logs:
            t = time.strptime(line[:19],'%Y-%m-%d %H:%M:%S')
            if t > end_time:
                break
            if t > start_time:
                print(line,end='')

def cut_log2():
    # 打开日志
    data = []
    with open(logfile,'r') as logs:
        for line in logs:
            time = line.split('|')[0]
            sql = line.split('|')[5]
            data.append(time)
            data.append(sql)
    # 定义一个新文件
    newlog=open('newlog',mode='a',encoding='utf-8')
    print(data,file=newlog)
    newlog.close()
 
if __name__ == '__main__':
    cut_log2()  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值