user3492006 user3492006 - 1 year ago 61
Python Question

Capture files that have been modified in the past x days in Python

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?

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 ="%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')
logger.setLevel(logging.INFO)'Getting list of files to re-encode...')
fileList = []
rootdir = 'T:\\''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'Adding %s to list of file to re-encode.' % theFile)

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

print '=======--------=======''=======--------=======')'Starting processing of files...')

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

print 'Processing',inFile'Processing %s' % inFile)
returncode =,outFile))
print 'Removing',inFile'Removing %s' % inFile)
os.remove(inFile)'Sending Pushover notification...')
conn = httplib.HTTPSConnection("")
conn.request("POST", "/1/messages.json",
"token": "TOKENHERE",
"user": "USERKEY",
"message": "Re-encoding complete for %s" % fileName,
}), {"Content-type": "application/x-www-form-urlencoded"})

Answer Source

os.path.getmtime(filename) will give you the modification time in seconds since the epoch.

Use the datetime module to convert it to a datetime object, and compare it as usual.

import datetime
import os

ONE_WEEK_AGO = - datetime.timedelta(days=7)

mod_date = datetime.datetime.fromtimestamp(os.path.getmtime(theFile))
if mod_date > ONE_WEEK_AGO:
    # use the file.