I have a folder directory (shown below) that contains folders titled "year-month." They will be continuously added over time. I am trying to write a python code that selects any files in folders dated in the last 12 months.
I've built code to always select the files in the current year-month folder and it works. If I ran this i'd get all the files in the 2024-06 folder since that is the current month and year. How can I modify this script to grab every folder from the last 12 months?
today = datetime.datetime.now()
year = today.strftime("%Y")
month=today.strftime("%m")
day=today.strftime("%d")
output = r"'F:\\6 - Business Units\\Sun Pacific Farming Cooperative\\B - General\\17 - GIS\\Drone Imagery\\RBG\\Monthly\\" + year +"-" + month + "\\'"
Here's a possible solution: The idea is to check the creation time of each file via Path.stat().st_ctime
and to build a list of files within the appropriate date range as defined by the oldest
timestamp (today - 365 days). The datetime
module handles calculating the timedelta
as well as formatting the st_ctime
info into a usable timestamp for comparison.
import datetime as dt
from pathlib import Path
root = Path('<your path here>')
oldest = dt.datetime.today() - dt.timedelta(days=365)
files = [
f for f in root.iterdir()
if dt.datetime.fromtimestamp(f.stat().st_ctime) >= oldest
]
print(files)