Adjusting timestamps on images with Python


As ever, mostly notes to myself.

I have a bunch of old images which don't have any timestamp associated with them. This quick Python script will add a DateTime EXIF metadata tag to an image.

This uses piexif which can be installed using

pip install piexif

This simple script reads a photo, adds a timestamp, then saves a copy of the new photo.

from PIL import Image
from PIL.ExifTags import TAGS
import piexif
from datetime import datetime

im = Image.open("test.jpg")
exif_dict = piexif.load(im.info["exif"])

exif_dict["0th"][piexif.ImageIFD.DateTime]=datetime.strptime("2000/12/25 12:32","%Y/%m/%d %H:%M").strftime("%Y:%m:%d %H:%M:%S")
exif_bytes = piexif.dump(exif_dict)
im.save("new.jpg", "jpeg", exif=exif_bytes, quality="keep", optimize=True)

A point to note about the last line. By default, PIL saves JPGs with a quality of 75. By using quality="keep" the original quality is preserved. The optimize=True attempts to losslessly improve the image.

A word of warning - timestamps are stored in multiple EXIF locations. If your image already has a timestamp, it is possible that this script won't change it.


Share this post on…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

One thought on “Adjusting timestamps on images with Python”

  1. Johan says:

    Thanks ! I was stuck on this and from stackoverflow to chatgpt I had no help 🙂

    Reply

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">