Terence Eden. He has a beard and is smiling.
Theme Switcher:

Adjusting timestamps on images with Python

· 1 comment · 200 words · Viewed ~3,482 times


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…

One thought on “Adjusting timestamps on images with Python”

  1. 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.

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

To respond on your own website, write a post which contains a link to this post - then enter the URl of your page here. Learn more about WebMentions.