Categories We Write About

Rename photos by date using Python

Renaming photos by date using Python is a common task that can be automated efficiently by reading the metadata (EXIF data) of the images to extract the date they were taken, then renaming the files accordingly. Here’s a detailed guide and a complete Python script to do this.


How to Rename Photos by Date in Python

Key Steps:

  1. Read image files from a folder

  2. Extract the date the photo was taken (usually stored in EXIF metadata)

  3. Format the date into a filename-friendly string

  4. Rename the files based on this date


Required Libraries

  • Pillow (PIL): To read EXIF metadata from images

  • os: To handle file system operations

  • shutil (optional): To move files if needed

Install Pillow if you don’t have it:

bash
pip install pillow

Python Script to Rename Photos by Date

python
import os from PIL import Image from PIL.ExifTags import TAGS from datetime import datetime def get_date_taken(path): """Extract the date the photo was taken from EXIF data.""" try: image = Image.open(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 except Exception as e: print(f"Error reading EXIF data from {path}: {e}") return None def format_date(date_str): """Format EXIF date string into 'YYYY-MM-DD_HH-MM-SS' format.""" try: # Typical EXIF date format: "YYYY:MM:DD HH:MM:SS" date_obj = datetime.strptime(date_str, '%Y:%m:%d %H:%M:%S') return date_obj.strftime('%Y-%m-%d_%H-%M-%S') except Exception as e: print(f"Error formatting date string {date_str}: {e}") return None def rename_photos_by_date(folder_path): """Rename all photos in the folder by their date taken.""" supported_extensions = ('.jpg', '.jpeg', '.png', '.tiff', '.heic') # Add more if needed for filename in os.listdir(folder_path): if filename.lower().endswith(supported_extensions): full_path = os.path.join(folder_path, filename) date_taken = get_date_taken(full_path) if date_taken: formatted_date = format_date(date_taken) if formatted_date: # Prepare new filename extension = os.path.splitext(filename)[1].lower() new_filename = f"{formatted_date}{extension}" new_full_path = os.path.join(folder_path, new_filename) # Handle duplicates by appending a counter counter = 1 while os.path.exists(new_full_path): new_filename = f"{formatted_date}_{counter}{extension}" new_full_path = os.path.join(folder_path, new_filename) counter += 1 os.rename(full_path, new_full_path) print(f"Renamed '{filename}' to '{new_filename}'") else: print(f"Could not format date for file: {filename}") else: print(f"No date found in EXIF for file: {filename}") if __name__ == "__main__": folder = input("Enter the folder path containing photos: ") rename_photos_by_date(folder)

Explanation:

  • get_date_taken(): Opens the image and reads the DateTimeOriginal EXIF tag, which usually holds when the photo was taken.

  • format_date(): Converts the EXIF date string from YYYY:MM:DD HH:MM:SS to a filename-friendly format YYYY-MM-DD_HH-MM-SS.

  • rename_photos_by_date(): Iterates over supported image files, renames them using the date, and handles duplicate names by appending a counter.

  • The script prompts you for the folder path where the images are stored.


Notes:

  • Some images may lack EXIF data or the DateTimeOriginal tag, especially screenshots or images downloaded from the web.

  • You can extend the script to use file creation or modification time as a fallback if no EXIF date is found.

  • This script currently supports common photo file extensions; add or remove extensions as needed.


If you want, I can help you modify the script to include fallback methods or to handle videos too!

Share This Page:

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

We respect your email privacy

Categories We Write About