You can get the last accessed time with os.path.getatime('/path/to/your/file')
. Also, last modification time (os.path.getmtime
) and creation time (os.path.getctime
). More on those here. But these are in UNIX epoch format. So you should first convert the time you want to UNIX epoch format with the following command:
from datetime import datetime as dt
# Create the time you want
t = dt(2022, 11, 4, 18, 8, 30)
# Convert to UNIX epoch time
converted = t.timestamp()
# Output: 1667572710.0
Now you can check each file's modification/access/creation time and do the comparison, then delete ones you want
import os
from datetime import datetime as dt
# List files in the current directory
list_of_files = os.listdir()
for f in list_of_files:
# Creation time
ct = os.path.getctime(f)
# Modification time
mt = os.path.getmtime(f)
# Check the human readable string
print(f"file: {f} "
f"creation: {dt.fromtimestamp(ct)} "
f"modification: {dt.fromtimestamp(mt)} ")
But be careful about converting time-zones! You don't want to give the code a local time zone and remove the files based on UTC
Some useful resources: