Reputation: 319
I am trying to delete files from a folder based off of the date modified, inside the folder are files with Date modified as follows:
Name Date modified
File 1 9/12/2017 1:34 PM
File 2 9/12/2017 1:38 PM
File 3 9/12/2017 12:00 PM
File 4 9/12/2017 12:00 PM
File 5 9/12/2017 7:40 AM
File 6 9/12/2017 7:40 AM
Lets say I just want to keep files in this folder that are only 30 minutes old and lets just say right now it is 1:48 PM so what I would expect to be kept after running the cleanup script which would delete the files that are older than 30 minutes would be:
Name Date modified
File 1 9/12/2017 1:34 PM
File 2 9/12/2017 1:38 PM
Thanks in advance.
Upvotes: 0
Views: 9671
Reputation: 1059
you can try something like this:
import os
import time
now = time.time()
folder = '<folder_path>'
files = [os.path.join(folder, filename) for filename in os.listdir(folder)]
for filename in files:
if (now - os.stat(filename).st_mtime) > 1800:
command = "rm {0}".format(filename)
subprocess.call(command, shell=True)
time.time()
returns the actual time in seconds.
os.stat(filename).st_mtime
returns the time of last modification in seconds.
1800 is 30 minutes in seconds.
Upvotes: 3