python中判断时间间隔的问题

2025-03-23 15:10:00
推荐回答(1个)
回答1:

代码有点烂,不过还算能解决问题

注释比较详细了

# -*- coding: utf-8 -*-

import datetime

__author__ = 'lpe234'
__date__ = '2015-04-26'

f = file('1.txt')

file_content = f.readlines()
all_lines = len(file_content)


def get_(content):
    """
    递归调用
    :param content:
    :return:
    """
    # 判断当前内容行数是否大于2
    if len(content) > 1:
        line_1 = content[0]
        line_2 = content[1]
        # 读取当前内容的第一行 和 第二行,并分别对比内容是否一致
        loc1, date1, time1, type1, no1 = line_1.split()
        loc2, date2, time2, type2, no2 = line_2.split()
        # 判断 除了time 以外的数据是否一致
        if loc1 == loc2 and date1 == date2 and type1 == type2 and no1 == no2:
            # 判断时间 是否符合要求
            if (datetime.datetime.strptime(time2, '%H:%M:%S')-datetime.datetime.strptime(time1, '%H:%M:%S')).seconds\
                    in range(4):
                # 符合要求,则打印
                print line_1, line_2.replace('\n', '')
            # 递归
            return get_(content[2:])
        else:
            # 递归
            return get_(content[1:])
    else:
        pass

# 去掉 第一行 :地点    时间    类型    工号
get_(file_content[1:])

输出结果:

C:\Python27\python.exe D:/00/gui/text/1.py
上海        2015-04-24 11:25:03    1    123
上海        2015-04-24 11:25:03    1    123
北京        2015-04-24 11:25:13    1    127
北京       2015-04-24 11:25:15    1    127
广州        2015-04-24 11:25:16    2    125
广州        2015-04-24 11:25:17    2    125

Process finished with exit code 0