Skip to content
Advertisement

How to get the latest file update in last six hours in a folder using python

I am trying to write a python program lists the files updated/created in last six hour using python.

Advertisement

Answer

This will give you what you want, although you might want to be careful with timezone offset values –

import os
import datetime as dt

folder_loc = '.'
check_tm = dt.datetime.now() - dt.timedelta(hours=6)
files = os.listdir(folder_loc)
for file in files:
    file_loc = os.path.join(folder_loc, file)
    updated_tm = os.path.getmtime(file_loc)
    updated_dt = dt.datetime.fromtimestamp(updated_tm)
    if updated_dt > check_tm:
        print('{} was updated within 6 hours'.format(file_loc))

Hope this helps.

Advertisement