Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fix_exif_timestamps
#!/usr/bin/env python
"""Recursively scan a directory tree, fixing dates
on all jpg/png image files.
Modifications are done in-place.
Requires: gexiv2
Loosely based on: http://coreygoldberg.blogspot.de/2014/01/python-fixing-my-photo-library-dates.html
"""
import os
from datetime import datetime as dt
from datetime import timedelta as timedelta
# GObject-based wrapper around the Exiv2 library.
# Ubuntu/Debian: apt-get install gir1.2-gexiv2-0.10 libgexiv2-2
# Mac OS X: brew install gexiv2
# Arch Linux: pacman -S libgexiv2
import gi
gi.require_version('GExiv2', '0.10')
from gi.repository import GExiv2
def fix_image_dates(img_path, td, dry_run=True):
t = os.path.getctime(img_path)
exif = GExiv2.Metadata(img_path)
orig_ts = exif['Exif.Image.DateTime']
orig_dt = dt.strptime(orig_ts, '%Y:%m:%d %H:%M:%S')
fixed_dt = orig_dt + td
fixed_ts = fixed_dt.strftime('%Y:%m:%d %H:%M:%S')
print(img_path, " - Converting ", orig_ts, " -> to ", fixed_ts)
if dry_run: return
#print(exif['Exif.Image.DateTime'])
#print(exif['Exif.Photo.DateTimeDigitized'])
#print(exif['Exif.Photo.DateTimeOriginal'])
exif['Exif.Image.DateTime'] = fixed_ts
exif['Exif.Photo.DateTimeDigitized'] = fixed_ts
exif['Exif.Photo.DateTimeOriginal'] = fixed_ts
exif.save_file()
os.utime(img_path, (t, t))
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--days', type=float, default=0)
parser.add_argument('--hours', type=int, default=0)
parser.add_argument('--minutes', type=float, default=0)
parser.add_argument('--seconds', type=float, default=0)
parser.add_argument('--add', '-a', action='store_true')
parser.add_argument('--subtract', '-s', action='store_true')
parser.add_argument('--dry-run', '-d', action='store_true')
parser.add_argument('folder', default='.')
args = parser.parse_args()
if not args.add and not args.subtract: parser.error('Please select --add or --subtract')
if args.add and args.subtract: parser.error('Select either --add or --subtract')
td = timedelta(days=args.days, hours=args.hours, minutes=args.minutes, seconds=args.seconds)
if args.subtract: td = -td
for root, dirs, file_names in os.walk(args.folder):
for file_name in file_names:
if file_name.lower().endswith(('jpg', 'png')):
img_path = os.path.join(root, file_name)
fix_image_dates(img_path, td, dry_run=args.dry_run)
if __name__ == '__main__': main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.