Skip to main content
 首页 » 编程设计

python 2 : Compare a timestamp between two points in time

2024年12月31日8lautakyan007

对于我的脚本,我只需要使用带有标准库的 Python 2.6。我正在尝试编写一个脚本来遍历日志目录,该目录定义了一个条件,该条件仅匹配具有适当时间戳的日志。我使用的时间戳来自文件名。我不想使用操作系统时间戳,因为有时文件会被复制到不同的目录以防止它们被覆盖,这会改变文件的修改时间。

每 200MB 创建一个新文件。文件名上的时间戳是文件的创建时间,代表文件中最早的日志条目。

import datetime 
 
# One event might span multiple log files. 
call_start = datetime.datetime(2018, 5, 15, 5, 25, 9) 
call_stop = datetime.datetime(2018, 5, 15, 5, 37, 38) 
 
# Timestamp values of file generated from file's naming convention 
t1 = datetime.datetime(2018, 5, 15, 4, 48, 16) 
t2 = datetime.datetime(2018, 5, 15, 5, 3, 53) 
t3 = datetime.datetime(2018, 5, 15, 5, 19, 14) 
t4 = datetime.datetime(2018, 5, 15, 5, 35) 
t5 = datetime.datetime(2018, 5, 15, 5, 49, 19) 
 
file_times = [t1, t2, t3, t4, t5] 
 
matching_times = [] 
for ftime in file_times: 
    # Logic I can't figure out 
    if scratches_head: 
        matching_times.append(ftime) 
 
# I would expect the matching_times list to contain t3 and t4 

编辑

来自 comments 的澄清:

t3 是在 5:19:14am 创建的文件。 call_start 是我在日志中看到的第一个条目。它从 5:25:09am 开始。由于 t4 直到 5:35:00am 才创建,因此 call_start 必须在 t3 中。 call_stop 是我要查找的最后一个日志条目。我会在 t4,因为 t5 是在 5:49:19am 创建的。

请您参考如下方法:

一种方法是对列表中的项目enumerate() 并从每对连续的时间创建范围。然后检查是否有这些 ranges overlap使用 (call_start, call_end)。如果范围重叠,请将范围的开头附加到列表中。您还必须在列表中最后一次包含在特殊检查中。

例如:

for i, ftime in enumerate(file_times): 
    if i+1 >= len(file_times): 
        # last item in list, add if it's less than call_stop 
        scratches_head = ftime < call_stop 
    else: 
        # check if ranges overlap 
        fstart = ftime 
        fend = file_times[i+1] 
        scratches_head = (fstart <= call_stop) and (fend >= call_start) 
 
    if scratches_head: 
        matching_times.append(ftime) 
 
print([datetime.datetime.strftime(x, "%Y-%m-%d %H:%M:%S") for x in matching_times]) 
#['2018-05-15 05:19:14', '2018-05-15 05:35:00']