在Python中:检查文件修改时间是否早于特定日期时间

Luk*_*uke 9 python datetime

我在c#中编写了这段代码来检查文件是否过时:

 DateTime? lastTimeModified = file.getLastTimeModified();
        if (!lastTimeModified.HasValue)
        {
            //File does not exist, so it is out of date
            return true;
        }
        if (lastTimeModified.Value < DateTime.Now.AddMinutes(-synchIntervall))
        {
            return true;
        } else
        {
           return false;
        }
Run Code Online (Sandbox Code Playgroud)

我如何在python中写这个?

我在python中试过这个.

statbuf = os.stat(filename)
if(statbuf.st_mtime < datetime.datetime.now() - self.synchIntervall):
    return True
 else:
    return False
Run Code Online (Sandbox Code Playgroud)

我得到以下异常

message str: unsupported operand type(s) for -: 'datetime.datetime' and 'int'   
Run Code Online (Sandbox Code Playgroud)

mac*_*mac 18

您想使用该os.path.getmtime功能(与time.time一个功能结合使用).这应该给你一个想法:

>>> import os.path as path
>>> path.getmtime('next_commit.txt')
1318340964.0525577
>>> import time
>>> time.time()
1322143114.693798
Run Code Online (Sandbox Code Playgroud)

  • 这个奇怪的数字到底说明了什么?我如何将它与日期进行比较? (3认同)
  • 对@mac答案稍加调整即可使其完整:`import os.path as path import time def is_file_older_than_x_days(file,days = 1):file_time = path.getmtime(file)#检查24小时是否(time.time() -file_time)/ 3600&gt; 24 * days:print('早于%s days'%days),否则:print('不早于%s days'%days)` (2认同)

Jon*_*han 13

@E235 在接受的答案中的评论对我来说非常有效。

这里已经格式化了;

import os.path as path
import time

def is_file_older_than_x_days(file, days=1): 
    file_time = path.getmtime(file) 
    # Check against 24 hours 
    return ((time.time() - file_time) / 3600 > 24*days)
Run Code Online (Sandbox Code Playgroud)


rou*_*ble 6

这是一个使用 timedelta 的通用解决方案,适用于甚至......

from datetime import datetime

def is_file_older_than (file, delta): 
    cutoff = datetime.utcnow() - delta
    mtime = datetime.utcfromtimestamp(os.path.getmtime(file))
    if mtime < cutoff:
        return True
    return False
Run Code Online (Sandbox Code Playgroud)

这可以如下使用。

要检测超过 10 秒的文件:

from datetime import timedelta

is_file_older_than(filename, timedelta(seconds=10))
Run Code Online (Sandbox Code Playgroud)

要检测超过 10 天的文件:

from datetime import timedelta

is_file_older_than(filename, timedelta(days=10))
Run Code Online (Sandbox Code Playgroud)

如果您可以安装外部依赖项,您还可以执行数月和数年:

from dateutil.relativedelta import relativedelta # pip install python-dateutil

is_file_older_than(filename, relativedelta(months=10))
Run Code Online (Sandbox Code Playgroud)