python获取两个时间间隔的天数

前言:

作者:神的孩子在歌唱

大家好,我叫智

今天做项目的时候有一个定时清理日志的需求,可是linux里面无法获取到文件的创建时间了,只能获取状态和更新时间,由于目前日志是存在同一个log中的(如下图),只要到达一定时间就把这个文件删除就可以,所以只要通过正则获取第一条日志产生的时间就知道他创建的时间了。

在这里插入图片描述

不多说,上代码:

import datetime
def dif_time(date):
    # 使用datetime类型计算两个时间之间差值
    now_time = datetime.datetime.now()
    now_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
    d1 = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    d2 = datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S')
    #间隔天数
    day = (d2 - d1).days
    #间隔秒数
    second = (d2 - d1).seconds
    print (day)  
    print (second)  #注意这样计算出的秒数只有小时之后的计算额 也就是不包含天之间差数

with open('E:\\study\\test\\webssh.log', encoding='utf-8') as file:
    content_list = file.readlines()  # 读取所有行并返回列表
    contentall = [x.strip() for x in content_list]
    if content_list.__len__() >3:
        print(content_list[2])
        pattern = re.compile(r'\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}')
        res = pattern.match(content_list[2])
        print(res.group())
        dif_time(res.group())

参考文章:

https://blog.csdn.net/TFATS/article/details/103871445

python 读取一个log文件:https://www.csdn.net/tags/MtzaIgysNTIzNDQtYmxvZwO0O0OO0O0O.html

本人csdn博客:https://blog.csdn.net/weixin_46654114

转载说明:跟我说明,务必注明来源,附带本人博客连接。

猜你喜欢

转载自blog.csdn.net/weixin_46654114/article/details/125677691