You are on page 1of 2

import os

import shutil
from PIL import Image
from datetime import datetime

# Function to extract the 'Date Taken' from an image's EXIF data


def get_exif_date_taken(file_path):
try:
with Image.open(file_path) as img:
exif_data = img._getexif()
if exif_data:
# DateTimeOriginal and DateTimeDigitized tags
for tag in (36867, 36868):
if tag in exif_data:
date_str = exif_data[tag]
return datetime.strptime(date_str, "%Y:%m:%d %H:%M:%S")
except Exception as e:
print(f"Error retrieving EXIF data: {e}")
return None

# Function to get the earliest date from the file system and EXIF data
def get_earliest_date(file_path):
# Get 'Date Created' and 'Date Modified' from the file system
stat = os.stat(file_path)
date_created = datetime.fromtimestamp(stat.st_ctime) # Creation time
date_modified = datetime.fromtimestamp(stat.st_mtime) # Last modified time

# Get 'Date Taken' from EXIF data


exif_date_taken = get_exif_date_taken(file_path)

# Compile all dates into a list, filtering out any Nones


dates = [date for date in [date_created, date_modified, exif_date_taken] if
date]

# Return the earliest date


return min(dates)

# Function to organize images into folders based on the earliest of the dates
def organize_images_by_date(image_directory):
for filename in os.listdir(image_directory):
if filename.lower().endswith((".jpg", ".png", ".jpeg")): # Include other
image formats if necessary
file_path = os.path.join(image_directory, filename)
earliest_date = get_earliest_date(file_path)

if earliest_date:
# Format the folder name as 'Jan, 2013'
month_year_folder = earliest_date.strftime("%b, %Y")
target_directory = os.path.join(image_directory, month_year_folder)

# Create the target directory if it doesn't exist


if not os.path.exists(target_directory):
os.makedirs(target_directory)

# Move the file to the target directory


shutil.move(file_path, os.path.join(target_directory, filename))

# Provide the path to the directory containing your images


image_directory = 'D:\Pic_Dir'
organize_images_by_date(image_directory)

You might also like