【问题标题】:how to print lines between two time stamps using Python 3?如何使用 Python 3 打印两个时间戳之间的行?
【发布时间】:2015-11-02 10:28:08
【问题描述】:

如何过滤掉两个时间戳之间的行并仅在 Python 中打印这些行?

示例:我想过滤 08:00:00 am 到 05:00:00 pm 我尝试了类似的方法,但它不起作用。

 def ipaddr(w):
    print("====Welcome to HTTP log Debugger ==== ")
    file= input("Please Enter log File path: ")
    start_time = input("start Time: ")
    End_time = input("End Time : ")
    with open(file,'r') as f:
        lines = f.read().splitlines()
    for L in lines:
        if L.startswith(start_time):
            p= 1
        elif L.startswith(End_time):
            p=0
            break
        if p: print(L)

【问题讨论】:

  • 提供样本输入数据。请阅读this
  • 并且比“它不起作用”更具体

标签: python python-3.x


【解决方案1】:
D1 = 1 #starting date

D2 = 10 # for ending date

clock1 = 8 # for 8'O clock
clock2 = 17 # for up to 17:59::59 

month_int = 1 # for jan
Clock= "{0:0=2d}".format(D1)

for i in range(clock1+1,clock2):
    Clock = Clock+"|"+"{0:0=2d}".format(i)


import calendar
month = calendar.month_name[month_int]

s= "{0:0=2d}".format(D1)

for i in range(D1+1,D2):
    s = s+"|"+"{0:0=2d}".format(i)

with open('logfile.log', 'r') as f:
    for line in f:
            if re.match("\D{3}\s"+month+"\s("+s+")\s("+Clock+")", line):
                print line

【讨论】:

  • 我得到了一个新场景,如果日期是字符串格式,例如:Mon May 03 12:23:11: Tue May 04 11:00:10: 我希望日期和时间都需要过滤并打印必要的行
  • 根据我的更新,您将在 5 月 3 日至 6 日从08:00 to 16:59 收到
  • 因为它是硬编码的..我需要用户输入,这应该是通用的,你能帮我吗
  • 您可以尝试两个循环,一个用于日期过滤,另一个用于时间过滤。你需要标准化时间格式
  • @RAM 我为你更新了代码。唯一的缺点是它只能在同一个日历月找到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2021-09-09
  • 2018-01-18
  • 1970-01-01
  • 2021-03-11
  • 2017-05-12
相关资源
最近更新 更多