python按修改时间过滤文件

标签 python logging time

我有以下代码:

def filter_by_time(files):
    print "---List of log files to timecheck: "
    for f in files:
        print f, datetime.datetime.fromtimestamp(os.path.getmtime(f))
    print "------"

    mins = datetime.timedelta(minutes=int(raw_input("Age of log files in minutes? ")))
    print "Taking ", mins, "minutes"
    mins = mins.total_seconds()
    current = time.time()
    difftime = current - mins
    print "current time: ", datetime.datetime.fromtimestamp(current)
    print "logs from after: ", datetime.datetime.fromtimestamp(difftime)   

    for f in files:    
        tLog = os.path.getmtime(f)
        print "checking ", f, datetime.datetime.fromtimestamp(tLog)
        if difftime > tLog:
            print "difftime is bigger than tLog", "removing ", f
            files.remove(f)

    print "*****List of log files after timecheck"
    for f in files:
        print f, datetime.datetime.fromtimestamp(os.path.getmtime(f)) 
    print "******"  
    return files

以及一些日志文件样本。 当我输入几分钟时,上面代码的输出是:

List of log files to timecheck: 

1copy2.log  11:59:40

1copy3.log  12:13:53

1copy.log  11:59:40

1.log  11:59:40

Age of log files in minutes? 5

Taking  0:05:00 minutes

current time:  2015-07-14 14:02:11.861755

logs from after:  2015-07-14 13:57:11.861755

checking  1 copy 2.log 2015-07-14 11:59:40

difftime is bigger than tLog removing  1copy2.log

checking  1copy.log 2015-07-14 11:59:40

difftime is bigger than tLog removing  1copy.log

List of log files after timecheck



1copy3.log 2015-07-14 12:13:53

1.log 2015-07-14 11:59:40



Collected: 1copy3.log

Collected: 1.log

如您所见,它收集的文件不正确。它所做的是检查 4 个文件以查看在过去 5 分钟内是否有任何文件被修改。它从列表中删除了 2 个,但应该删除了 4 个文件。

(进行了一些编辑以便于阅读)

最佳答案

考虑 Python 中可用的 filter 函数。我假设您的输入是一个文件列表和您要检查的过去几分钟,并且您希望根据 min< 之间的时间段内最后修改的文件过滤文件 过去和现在的分钟数。

import datetime, os
def files_after (files, min)
    lower_time_bound = datetime.datetime.now() - timedelta(minutes=min)
    return filter(lambda f: datetime.datetime.fromtimestamp(os.path.getmtime(f)) > lower_time_bound, files)

关于python按修改时间过滤文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31408524/

相关文章:

python - Tensorflow MNIST 教程 - 测试精度非常低

PHP SQL 日期时间问题

sql-server - 将 int 转换为时间(奇怪的值)

linux - 在一定时间后中止程序

python - .NET框架中使用的经过训练的 tensorflow 模型

python - SQLAlchemy - 访问反射表的别名列时出现 NoReferencedTableError 异常

python - 是 python multiprocessing.Process start() 和 subprocess.Popen 做同样的工作

javascript - 设置 Pino 级别给我 'log_1.default.level is not a function'

python SIP日志文件处理

java - 如何记录到显式 AWS CloudWatch 日志流并以编程方式更改它 (Java/Scala/log4j)