import os import subprocess from datetime import datetime from PIL import Image from pillow_heif import register_heif_opener register_heif_opener() for file in os.listdir(): if (file.endswith(".JPG") or file.endswith(".HEIC")): im = Image.open(file) date = im.getexif().get(306) if date is None: print(f"no exif for {file}") continue dir = date[:7].replace(":", "-") os.makedirs(dir, exist_ok=True) os.rename(file, f"{dir}/{file}") elif file.endswith(".MOV"): ffprobe = subprocess.run(["ffprobe", file], check=True, stderr=subprocess.PIPE) output = ffprobe.stderr raw_date = None for line in output.decode().splitlines(): if line.startswith(" creation_time"): raw_date = line.split(":", 1)[1].strip() break if raw_date is None: continue creation_date = datetime.strptime(raw_date, "%Y-%m-%dT%H:%M:%S.%fZ") dir = f"{creation_date.year}-{creation_date.month}" os.makedirs(dir, exist_ok=True) os.rename(file, f"{dir}/{file}") else: continue