Capture files that have been modified in the past x days in Python
<p>I'm using the below script to re-encode my existing media files to MP4 using the HandBrake CLI. It's going to be a long process, so I'd like to have a way to capture files that have been created in the past 7 days, as well as the other filters (on file extensions), so that new content can be updated, while older content can be run on a separate script at different times. What do I have to change in the script to only capture files created in the past 7 days?</p>

<pre><code>import os
import time
import subprocess
import sys
import httplib
import urllib
from xml.dom import minidom
import logging
import datetime

#Script Directory setup
myDateTime = datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
logdir = 'D:\\logs\\'
logfile = logdir + 'TV_encode-' + myDateTime + '.log'

#Log Handler Setup
logger = logging.getLogger('TV_encode')
hdlr = logging.FileHandler(logfile)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

logger.info('Getting list of files to re-encode...')
fileList = []
rootdir = 'T:\\'
logger.info('Using %s as root directory for scan...' % rootdir)
for root, subFolders, files in os.walk(rootdir):
    for file in files:
        theFile = os.path.join(root,file)
        fileName, fileExtension = os.path.splitext(theFile)
        if fileExtension.lower() in ('.avi', '.divx', '.flv', '.m4v', '.mkv', '.mov', '.mpg', '.mpeg', '.wmv'):
            print 'Adding',theFile
            logger.info('Adding %s to list of file to re-encode.' % theFile)
            fileList.append(theFile)

runstr = '"C:\\Program Files\\Handbrake\\HandBrakeCLI.exe" -i "{0}" -o "{1}" --preset="Normal" --two-pass --turbo'

print '=======--------======='
logger.info('=======--------=======')
logger.info('Starting processing of files...')

while fileList:
    inFile = fileList.pop()
    logger.info('Original file: %s' % inFile)
    fileName, fileExtension = os.path.splitext(inFile)
    outFile = fileName+'.mp4'
    logger.info('New file: %s' % outFile)

    print 'Processing',inFile
    logger.info('Processing %s' % inFile)
    returncode  = subprocess.call(runstr.format(inFile,outFile))
    time.sleep(5)
    print 'Removing',inFile
    logger.info('Removing %s' % inFile)
    os.remove(inFile)

    logger.info('Sending Pushover notification...')
    conn = httplib.HTTPSConnection("api.pushover.net:443")
    conn.request("POST", "/1/messages.json",
                 urllib.urlencode({
                     "token": "TOKENHERE",
                     "user": "USERKEY",
                     "message": "Re-encoding complete for %s" % fileName,
                 }), {"Content-type": "application/x-www-form-urlencoded"})
    conn.getresponse()
</code></pre>

<p><code>os.path.getmtime(filename)</code> will give you the modification time in seconds since the epoch.</p>

<p>Use the <code>datetime</code> module to convert it to a <code>datetime</code> object, and compare it as usual.</p>

<pre><code>import datetime
import os

ONE_WEEK_AGO = datetime.datetime.today() - datetime.timedelta(days=7)

mod_date = datetime.datetime.fromtimestamp(os.path.getmtime(theFile))
if mod_date &gt; ONE_WEEK_AGO:
    # use the file.
</code></pre>

python handbrake