'Picking a range of latest files using their os status times

Is there a way of picking latest files by specifying a range of time using os.stat().st_mtime library. Let's say for example I want to pick every file which has been added into a directory within a range of the latest last 5 minutes.

The code I have been using below only picks the most recent file using os.stat().st_mtime library, the [0] index is obviously picking the first file.

study_dir = sorted(subdirs, key=lambda dir: os.stat(dir).st_mtime, reverse=True)[0]

What I want to achieve is specifying a range of all the files received in a directory within the last 5 minutes for instance, not to specify the number of files using indexing or slicing methods which will limit you to a specific number of file(s).

So the imagination of the code I want will be like:

os.stat(dir).<All files that have been received within the last 300 seconds>

The whole code of what I want to achieve is as below:

def get_filepaths(directory):
    """
    This function will generate the file names in a directory
    tree by walking the tree either top-down or bottom-up. For each
    directory in the tree rooted at directory top (including top itself),
    it yields a 3-tuple (dirpath, dirnames, filenames).
    """


    file_paths = [] # List which will store all of the full filepaths

    # Walk the tree.
    
    subdirs = [os.path.join(directory, d)
    for d in os.listdir(directory) if
            os.path.isdir(os.path.join(directory
            , d))]

    # Get the latest directory
    study_dir = sorted(subdirs, key=lambda dir: os.stat(dir).st_mtime, reverse=True)[0] 
    
    for root, directories, files in os.walk(study_dir):
        for filename in files:
            # Join the two strings in order to form the full filepath.
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)  # Add it to the list.
            
    return file_paths  # Self-explanatory.

# Run the above function and store its results in a variable.
test_dicoms = get_filepaths("/home/wisdom/Desktop/CT_CONVERSION_SYSTEM/Dicom_files")


Solution 1:[1]

Just filter by the mtime instead of sorting by it.

range = time.time() - 5 * 60
study_dir = [d for d in subdirs if os.stat(d).st_mtime >= range]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1