pythonwindowspython-2.7timestampfilemtime

Listing files timestamped within last two hours in Python


I have a directory full of files that are generated every 5 minutes. When I do an ls -l at a cmd prompt I can see the files and their last modified time.

I need to programatically get a list of files that are timestamped within the last N minutes. How to do that?


Solution

  • Use os.path.getmtime or os.path.getctime to get modification / creation time of the file.

    import os
    import time
    
    dirpath = '/path/to/dir'
    past = time.time() - 2*60*60 # 2 hours
    result = []
    for p, ds, fs in os.walk(dirpath):
        for fn in fs:
            filepath = os.path.join(p, fn)
            if os.path.getmtime(filepath) >= past:
                result.append(filepath)