Cannon
Cannon

Reputation: 319

How to delete files from a folder based on Date modified

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

Answers (2)

a.costa
a.costa

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

jabargas
jabargas

Reputation: 210

Please see this. Once you know how to get the date modified, compare it to your current system time and delete as needed. Please tell me if you need additional help. Sorry, this should've been a comment but I don't have enough rep yet :)

Upvotes: 0

Related Questions