Skip to content

Instantly share code, notes, and snippets.

@crockpotveggies
Created December 9, 2024 23:06
Show Gist options
  • Save crockpotveggies/7d722ae982f1322496999e105ab1a6ac to your computer and use it in GitHub Desktop.
Save crockpotveggies/7d722ae982f1322496999e105ab1a6ac to your computer and use it in GitHub Desktop.
Modify exif data to match album year
import os
import re
from datetime import datetime
import subprocess
def extract_date_from_folder(folder_name):
"""Extracts a date in the format YYYY-MM-DD, YYYY-MM, or YYYYs from a folder name."""
# Match full date YYYY-MM-DD
match_full = re.match(r"^(\d{4})-(\d{2})-(\d{2})", folder_name)
if match_full:
return f"{match_full.group(1)}-{match_full.group(2)}-{match_full.group(3)}"
# Match partial date YYYY-MM
match_partial = re.match(r"^(\d{4})-(\d{2})", folder_name)
if match_partial:
return f"{match_partial.group(1)}-{match_partial.group(2)}-01"
# Match decade format YYYYs
match_decade = re.match(r"^(\d{4})", folder_name)
if match_decade:
if int(match_decade.group(1)) < 1970:
return f"1970-01-01"
return f"{match_decade.group(1)}-01-01"
return None
def set_file_metadata(file_path, date):
"""Set the creation date metadata for a file using exiftool and SetFile."""
try:
# Format the date for EXIF metadata
formatted_exif_date = date.replace('-', ':') + " 00:00:00"
# Format the date for SetFile
formatted_setfile_date = datetime.strptime(date, "%Y-%m-%d").strftime("%m/%d/%Y %H:%M:%S")
# Update EXIF metadata
subprocess.run([
"exiftool",
"-overwrite_original",
f"-DateTimeOriginal={formatted_exif_date}",
file_path
], check=True)
# Update macOS file creation date using SetFile
subprocess.run([
"SetFile",
"-d",
formatted_setfile_date,
file_path
], check=True)
except subprocess.CalledProcessError as e:
print(f"Error setting metadata for {file_path}: {e}")
def process_photos_in_folder(base_folder):
"""Process all folders in the base directory to update photo metadata."""
for root, dirs, _ in os.walk(base_folder):
for folder in dirs:
folder_path = os.path.join(root, folder)
folder_date = extract_date_from_folder(folder)
if folder_date:
print(f"Processing folder: {folder_path} with date: {folder_date}")
for file in os.listdir(folder_path):
file_path = os.path.join(folder_path, file)
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
set_file_metadata(file_path, folder_date)
else:
print(f"Skipping folder: {folder_path} (no valid date found)")
if __name__ == "__main__":
base_folder = input("Enter the base folder path containing the albums: ")
if os.path.isdir(base_folder):
process_photos_in_folder(base_folder)
else:
print("The provided path is not a valid directory.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment