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

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

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))

@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)