Luke
Luke

Reputation: 5971

In Python: check if file modification time is older than a specific datetime

I wrote this code in c# to check if a file is out of date:

 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;
        }

How do I write this in python?

I tried this in python.

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

I got the following exception

message str: unsupported operand type(s) for -: 'datetime.datetime' and 'int'   

Upvotes: 19

Views: 31042

Answers (4)

rouble
rouble

Reputation: 18181

Here is a generic solution using timedelta, that works for seconds, days, months and even years...

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

This can be used as follows.

To detect a file older than 10 seconds:

from datetime import timedelta

is_file_older_than(filename, timedelta(seconds=10))

To detect a file older than 10 days:

from datetime import timedelta

is_file_older_than(filename, timedelta(days=10))

If you are ok installing external dependencies, you can also do months and years:

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

is_file_older_than(filename, relativedelta(months=10))

Upvotes: 10

Jonathan
Jonathan

Reputation: 11355

@E235's comment in the accepted answer worked really well for me.

Here it is formatted;

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)

Upvotes: 13

jonathan.hepp
jonathan.hepp

Reputation: 1643

The problem there is that your synchIntervall is not a datetime object so Python can't decrease it. You need to use another datetime object. like:

synchIntervall = datetime.day(2)

or

synchIntervall = datetime.hour(10)

or a more complete one:

synchIntervall = datetime.datetime(year, month, day, hour=0, minute=0, second=0)

the first three are required. This way you determinate the variable in a value which can be calculated with the datetime.datetime.now() value.

Upvotes: 1

mac
mac

Reputation: 43031

You want to use the os.path.getmtime function (in combination with the time.time one). This should give you an idea:

>>> import os.path as path
>>> path.getmtime('next_commit.txt')
1318340964.0525577
>>> import time
>>> time.time()
1322143114.693798

Upvotes: 26

Related Questions