Skip to content

Instantly share code, notes, and snippets.

@dgrant
Created May 2, 2015 05:16
Show Gist options
  • Save dgrant/5dd3d751cf88db45ad23 to your computer and use it in GitHub Desktop.
Save dgrant/5dd3d751cf88db45ad23 to your computer and use it in GitHub Desktop.
Shift EXIF times of pictures (fixes 'CreateDate', 'DateTimeOriginal', 'ModifyDate')
#!/usr/bin/env python3
import datetime
import argparse
import math
import os
import sys
import time
import subprocess
def parse_args():
def exists(path):
if os.path.exists(path):
return path
else:
raise argparse.ArgumentTypeError("File %s does not exist" % path)
parser = argparse.ArgumentParser()
parser.add_argument("--fake", "-f", action="store_true", default=False,
help="don't actually rename anything")
parser.add_argument("offset", type=int,
help="offset hours", metavar="HOURS")
parser.add_argument("files", type=exists, nargs="+", help="files to time shift")
return parser.parse_args()
def change_all_exif_dates(path, hours_shift, fake=False):
for tag in ('CreateDate', 'DateTimeOriginal', 'ModifyDate',):
cmd = ['exiftool', '-%s%s=%d' % (tag, '+' if hours_shift >= 0 else '-', abs(hours_shift)), path]
print("Running command:", " ".join(cmd))
if not fake:
subprocess.check_call(cmd)
def time_shift(files, offset, fake=False):
for f in files:
f = os.path.abspath(f)
orig_mtime = datetime.datetime.fromtimestamp(os.path.getmtime(f))
mtime = orig_mtime + datetime.timedelta(hours=offset)
if mtime != orig_mtime:
print("Adjusting timestamp on file from %s to %s" % (orig_mtime, mtime))
new_seconds = time.mktime(mtime.timetuple())
change_all_exif_dates(f, offset, fake)
if not fake:
os.utime(f, (new_seconds, new_seconds))
def main():
args = parse_args()
# Check that all the files exist
time_shift(args.files, args.offset, args.fake)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment