Categories We Write About

Organizing Photos by Date with Python

Organizing photos by date can be a tedious task, especially when you have thousands of images scattered across folders. Automating this process using Python not only saves time but also creates a neat, chronological structure that makes it easier to locate specific photos. This article walks you through how to organize photos by their date metadata with Python, covering everything from reading image metadata to sorting and moving files into date-based folders.

Understanding Photo Metadata and Date Information

Most digital photos contain embedded metadata called EXIF (Exchangeable Image File Format) data. This metadata stores details about the photo, including the date and time the photo was taken, camera settings, GPS coordinates, and more.

For organizing by date, the most relevant EXIF tag is usually the DateTimeOriginal, which indicates when the photo was captured. However, not all photos have EXIF data, especially screenshots or images edited by software that may strip metadata. In such cases, you can fall back on the file’s last modified or creation date.

Required Python Libraries

  • Pillow: A powerful image processing library to read image files and extract EXIF data.

  • os and shutil: For file and folder operations.

  • datetime: To handle date formatting and parsing.

You can install Pillow using pip:

bash
pip install Pillow

Step 1: Extract Date from Image Metadata

Here’s how you can extract the date from a photo’s EXIF data using Pillow:

python
from PIL import Image from PIL.ExifTags import TAGS def get_photo_date(file_path): try: image = Image.open(file_path) exif_data = image._getexif() if not exif_data: return None for tag_id, value in exif_data.items(): tag = TAGS.get(tag_id, tag_id) if tag == 'DateTimeOriginal': return value # Example format: '2023:04:15 10:20:30' except Exception as e: print(f"Error reading EXIF data from {file_path}: {e}") return None

The DateTimeOriginal tag typically returns a string formatted as YYYY:MM:DD HH:MM:SS. You will need to parse this to a Python datetime object.

Step 2: Parse Date String to Date Object

python
from datetime import datetime def parse_date(date_str): try: return datetime.strptime(date_str, '%Y:%m:%d %H:%M:%S') except Exception as e: print(f"Error parsing date string {date_str}: {e}") return None

Step 3: Fallback Date Retrieval

If the image lacks EXIF data or the date tag, you can use the file’s modification time as a fallback:

python
import os def get_file_modification_date(file_path): t = os.path.getmtime(file_path) return datetime.fromtimestamp(t)

Step 4: Organizing Photos into Date-Based Folders

The goal is to move or copy photos into folders named by year and month (e.g., 2023-04). Here’s how to put it all together:

python
import shutil def organize_photos_by_date(source_folder, destination_folder): for root, dirs, files in os.walk(source_folder): for file in files: if file.lower().endswith(('.jpg', '.jpeg', '.png', '.heic', '.tiff')): file_path = os.path.join(root, file) date_str = get_photo_date(file_path) date_obj = parse_date(date_str) if date_str else None if not date_obj: date_obj = get_file_modification_date(file_path) folder_name = date_obj.strftime('%Y-%m') target_folder = os.path.join(destination_folder, folder_name) os.makedirs(target_folder, exist_ok=True) target_path = os.path.join(target_folder, file) # Move the file to the new folder shutil.move(file_path, target_path) print(f"Moved {file} to {target_folder}")

Notes on File Handling

  • Moving vs Copying: shutil.move relocates the file, which frees up space but removes the original. Use shutil.copy2 if you want to keep the originals.

  • Handling Filename Collisions: If two photos have the same filename, moving them into the same folder will cause a conflict. You can add logic to rename files by appending numbers or timestamps to avoid overwriting.

Enhancing the Script: Handling Filename Conflicts

python
def get_unique_filename(folder, filename): base, ext = os.path.splitext(filename) counter = 1 new_filename = filename while os.path.exists(os.path.join(folder, new_filename)): new_filename = f"{base}_{counter}{ext}" counter += 1 return new_filename

Replace the target_path assignment in the organize_photos_by_date function:

python
unique_filename = get_unique_filename(target_folder, file) target_path = os.path.join(target_folder, unique_filename)

Step 5: Running the Script

Use the function by specifying your source folder (where your photos currently are) and the destination folder (where you want them organized):

python
source_folder = '/path/to/your/photos' destination_folder = '/path/to/organized/photos' organize_photos_by_date(source_folder, destination_folder)

Additional Tips

  • Support for More Formats: If you have images like RAW files or other formats, include those extensions in the check.

  • Parallel Processing: For thousands of images, you can optimize with threading or multiprocessing.

  • Backup First: Always test on a copy of your files to prevent accidental data loss.


Organizing photos by date with Python is efficient and customizable. By leveraging EXIF metadata and file system attributes, you can automate the tedious process of sorting photos into neat, date-based folders, making your photo library much easier to navigate and manage.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About