Skip to content

Instantly share code, notes, and snippets.

@biggers
Last active September 16, 2022 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biggers/725ef09714d3ee1cc9edaae01cb95466 to your computer and use it in GitHub Desktop.
Save biggers/725ef09714d3ee1cc9edaae01cb95466 to your computer and use it in GitHub Desktop.
rename JPEG image files by (date, time) from EXIF data -- "fork" / update of n3wtron/exifImageMover.py
#!/usr/bin/env python
from PIL import Image
import sys
import time
import os
from os import path
import shutil
from optparse import OptionParser
def main():
optParser = OptionParser("usage: %prog [options] images... ")
optParser.add_option("-p", "--prefix", help="New File Prefix Date Format",
action="store", type="string", dest="dateFormat",
default="%Y-%m-%d_")
optParser.add_option("-d", "--dry",
help="Shows only a rename, NO MOVE WILL BE PERFORMED",
action="store_true", dest='dry')
(options, args) = optParser.parse_args(sys.argv)
dateFormat = options.dateFormat
dry = options.dry
for imagePath in args[1:]:
try:
img = Image.open(imagePath)
except IOError:
print("File " + imagePath + "not found")
continue
try:
exif_data = img._getexif()
strImageDate = exif_data[306]
except TypeError:
print("No EXIF date Information found for file: " + imagePath)
continue
try:
imageDate = time.strptime(strImageDate, "%Y:%m:%d %H:%M:%S")
except ValueError as err:
print("EXIF time date bad", err)
strImageDate = '1900:01:01 00:00:01'
imageDate = time.strptime(strImageDate, "%Y:%m:%d %H:%M:%S")
newFileName = time.strftime(dateFormat, imageDate) + \
path.basename(imagePath)
dir_name = path.dirname(imagePath)
if dir_name == '':
dir_name = '.'
newPath = dir_name + os.sep + newFileName
if dry:
print(imagePath + " -> " + newPath)
else:
shutil.move(imagePath, newPath)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment