Rename Photos by Date Taken
This script reads the "date taken" stored inside each photo (the EXIF data) and renames the files in chronological order. Photos taken on the same day are numbered _001, _002, and so on.
# rename_photos.py
import sys
from datetime import datetime
from pathlib import Path
from collections import defaultdict
from PIL import Image
EXTENSIONS = {".jpg", ".jpeg"}
def date_taken(path):
"""Return (datetime, from_exif). Falls back to file modified time."""
try:
with Image.open(path) as img:
exif = img.getexif()
# 36867 = DateTimeOriginal (in Exif sub-IFD), 306 = DateTime
raw = exif.get_ifd(0x8769).get(36867) or exif.get(306)
if raw:
return datetime.strptime(raw.strip("\x00 ")[:19], "%Y:%m:%d %H:%M:%S"), True
except Exception:
pass
return datetime.fromtimestamp(path.stat().st_mtime), False
def main():
args = [a for a in sys.argv[1:] if a != "--dry-run"]
dry_run = "--dry-run" in sys.argv
folder = Path(args[0]) if args else Path(".")
photos = []
for p in folder.iterdir():
if p.is_file() and p.suffix.lower() in EXTENSIONS:
dt, from_exif = date_taken(p)
if not from_exif:
print(f"No EXIF date, using file date: {p.name}")
photos.append((dt, p.name, p))
photos.sort()
# Build the rename plan
counters = defaultdict(int)
plan = []
for dt, _, p in photos:
day = dt.strftime("%Y-%m-%d")
counters[day] += 1
new_name = f"{day}_{counters[day]:03d}{p.suffix.lower()}"
plan.append((p, folder / new_name))
if dry_run:
for old, new in plan:
print(f"{old.name} -> {new.name}")
print(f"\nDry run: {len(plan)} files would be renamed. Nothing changed.")
return
# Two-step rename so new names never clash with existing ones
temps = []
for old, new in plan:
tmp = old.with_name(old.name + ".renaming")
old.rename(tmp)
temps.append((tmp, new))
for tmp, new in temps:
tmp.rename(new)
print(f"Done: renamed {len(plan)} photos.")
if __name__ == "__main__":
main()
How to Run It on Windows
1. Install Python (skip this if you already have it)
- Download it from python.org/downloads.
- During installation, tick "Add Python to PATH" on the first screen.
2. Install the Pillow library, which the script uses to read photo data
- Press
Win + R, type cmd, and press Enter.
- Run:
pip install Pillow
3. Save the script
- Paste the code into Notepad.
- Save it as
rename_photos.py, for example on your Desktop. In the "Save as type" box, choose All Files so it isn't saved as .txt.
4. Back up your photos. Copy the folder somewhere safe first. This is just a precaution.
5. Do a dry run. This shows you the new names without changing anything:
cd %USERPROFILE%\Desktop
python rename_photos.py "C:\Users\YourName\Pictures\Holiday" --dry-run
Replace the path with your actual photo folder. A quick way to get it is to open the folder in File Explorer, click the address bar, and copy the path.
6. Rename for real. If the preview looks right, run the same command without --dry-run:
python rename_photos.py "C:\Users\YourName\Pictures\Holiday"
Notes
- If
python isn't recognized, try py instead (e.g. py rename_photos.py ...).
- Some photos may have no EXIF date, such as images from messaging apps or screenshots. For those, the script uses the file's modified date and prints a warning. That date may be wrong if the files were copied, so check those photos.
- The script handles
.jpg and .jpeg files. To include other formats, add them to EXTENSIONS, e.g. ".heic". HEIC files also need pip install pillow-heif plus a couple of extra lines of code.