zoukankan      html  css  js  c++  java
  • 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='')
  • 相关阅读:
    简单了解winform
    SqL语句基础之增删改查
    数据库之表
    数据库基本概念与操作
    搞死人不偿命的 Bank系统
    for的循环题
    .net framework 版本汇总
    LinqToEntity模糊查询的方法选择
    日常工作中的点滴:C# 根据字节长度截包含中文的字符串
    64位系统 IIS中应用程序池设置导致 访问数据库错误
  • 原文地址:https://www.cnblogs.com/liangbc/p/12690965.html
Copyright © 2011-2022 走看看