Search code examples
pythondatetimetimedelta

Get files created before x days, y hours and z minutes in python?


Hi I have the below program which should give me the list of files created before a given amount of time from the current time

def filesOlderThan(path,day,hour,mins):
    file_list = []
    for root, dirs, files in os.walk(path):
        for a in files:
            path1 = root + "\\"+ a
            sub_time = datetime.datetime.today() - datetime.timedelta(days=day,hours=hour,minutes=mins)
            r_time = time.mktime(sub_time.utctimetuple())
            c_time = os.path.getctime(path1)
            if(r_time < c_time):
                file_list.append(path1)
    count = len(file_list)
    return file_list,count

files,count = filesOlderThan("C:\\Arena\\sample",0,0,10)

print count
for a in files:
    print a

When I run the program

C:\Arena>python getFilesOlderThan.py  
0

The program works for values hour values, but does not work with the following input case

  1. I set the minutes to 10
  2. Create a file inside C:\Arena\Sample
  3. Run the program, the program does not give me the file.

Solution

  • r_time = time.mktime(sub_time.utctimetuple())
    

    You're comparing the file's timestamp in localtime withthe current time in UTC.

    You should use timetuple() instead of utctimetuple.

    You can make some minor improvements to your function, such as doing calculations using datetimes instead of timestamps, using datetime.now instead of today and using cross-platform os.join instead of hard-coded windows separators. It also seems unnecessary to calculate the len of the list inside the function - you can do it outside, if it's needed.

    def filesOlderThan(path,day,hour,mins):
        delta= datetime.timedelta(days=day,hours=hour,minutes=mins)
        now= datetime.datetime.now()
        file_list = []
        for root, dirs, files in os.walk(path):
            for a in files:
                path1 = os.path.join(root, a)
                c_time = datetime.datetime.fromtimestamp(os.path.getctime(path1))
                if(now - delta < c_time):
                    file_list.append(path1)
        return file_list
    

    Finally, if you ever plan on sending these timestamps to another system, remember to convert them to utc (both the file's and the current). You'll probably want to use pytz for that.