I wouldl like to query a date of when a photo was taken.. how may I do that?

Dani AI

Generated

Short answer: read the picture’s EXIF metadata and look for the DateTimeOriginal (or related) tag. ’s filesystem timestamp is useful for file-level timing, and correctly points toward camera metadata — below is a compact, practical Python example using Pillow plus a few notes on pitfalls and fallbacks.

from PIL import Image, ExifTags
import datetime
import os

def capture_time(path):
    with Image.open(path) as img:
        exif = img._getexif() or {}
    exif_by_name = { ExifTags.TAGS.get(k, k): v for k, v in exif.items() }
    dt = exif_by_name.get('DateTimeOriginal') or exif_by_name.get('DateTime') or exif_by_name.get('DateTimeDigitized')
    if dt:
        return datetime.datetime.strptime(dt, '%Y:%m:%d %H:%M:%S')
    # fallback: use file modification time if no EXIF timestamp is present
    return datetime.datetime.fromtimestamp(os.path.getmtime(path))

Notes and troubleshooting:

  • EXIF date strings use the format "YYYY:MM:DD HH:MM:SS"; parse with strptime as shown. If parsing fails, keep the raw string for investigation.
  • EXIF timestamps are usually naive (no timezone). If you need absolute UTC, look for GPSDateStamp/GPSTimeStamp (GPS times are UTC) or OffsetTimeOriginal (EXIF 2.3) when available. Treat absent offsets as local camera time.
  • Many workflows can strip EXIF (web services, editors); some formats (HEIC/AVIF) need extra libraries to read metadata. If Pillow returns no EXIF, try dedicated readers like exifread or the command-line exiftool for the most robust extraction.
  • For bulk or forensic work prefer exiftool (handles many edge cases), and for writing/updating EXIF use piexif or similar.

Recommended Answers

All 3 Replies

It can be as simple as this ...

import os
import time

# pick a file you have in the working directory
filename = "beachball.jpg"

# show file creation time
print( time.ctime(os.path.getctime(filename)) )

Keep in mind that vegaseat's solution will only show you when the photo was created in the filesystem. If you took the photo on a digital camera and then put it on your computer three days later, the creation date would not be the time the picture was taken.

A lot of cameras put information in the header of the jpeg file itself that might contain the date and time the photo was taken. I did a google search for "python jpeg metadata" and found a lot of results so you might be able to find a library to help you.

commented: good info +2

Thanks for the help guys.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.