Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'   
like image 868
Luke Avatar asked Nov 24 '11 13:11

Luke


People also ask

How can you tell how old a file is in Python?

Use stat. M_TIME to get the last modified time and subtract it from the current time.

How do I check if a specific time has passed in Python?

To measure time elapsed during program's execution, either use time. clock() or time. time() functions. The python docs state that this function should be used for benchmarking purposes.

How to get modification time of a file in Python?

The os.path.getmtime ('file_path') function returns a modification time in numeric timestamp in float. Pass ‘file path’ as an absolute or relative path to a file. Wrap creation and modification time in a datetime object. The modification time returned by the getmtime () is in a numeric timestamps format.

How to detect a file older than 3 months in Python?

To detect a file older than 3 months we can either approximate to 90 days: from datetime import timedelta is_file_older_than (filename, timedelta (days=90)) from dateutil.relativedelta import relativedelta # pip install python-dateutil is_file_older_than (filename, relativedelta (months=3))

How to get the creation and modification time of a file?

pathlib.Path ('file_path').stat ().st_ctime: To get file creation time but only on windows and recent metadata change time on Unix The below steps show how to use the os.path module and datetime module to get the creation and modification time of a file in Python. The os.path module implements some valuable functions on pathnames.

How to get the date and time in Python?

It can be obtained in Unix time (Epoch time, Posix time) but can be converted to date and time using the datetime module. os.stat_result — Miscellaneous operating system interfaces — Python 3.10.0 documentation You can get the following timestamps. The meaning differs depending on the OS, so be especially careful about the creation time.


1 Answers

Here is a generic solution using 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

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))
like image 88
rouble Avatar answered Oct 04 '22 15:10

rouble