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 ="test.jpg")
exif_dict = piexif.load(["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)"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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.