Skip to content

Instantly share code, notes, and snippets.

@Perlence
Last active December 22, 2015 04:29
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 Perlence/6417641 to your computer and use it in GitHub Desktop.
Save Perlence/6417641 to your computer and use it in GitHub Desktop.
Rename JPEG images with EXIF data according to date
import sys
import os
from datetime import datetime
from PIL import Image
# Keys of items that may contain date
items = [36868, 36867, 306]
# Output date format
format = '%Y-%m-%d %H.%M.%S'
for filename in sys.argv[1:]:
img = Image.open(filename)
EXIF = img._getexif()
del img
for item in items:
datestr = EXIF.get(item, '')
try:
date = datetime.strptime(datestr, '%Y:%m:%d %H:%M:%S')
break
except ValueError:
date = None
if date:
path, _ = os.path.split(filename)
_, ext = os.path.splitext(filename)
new_filename = os.path.join(path, date.strftime(format))
i = ''
while True:
try:
os.rename(filename, new_filename + i + ext)
print '%s -> %s' % (filename, new_filename + i + ext)
break
except:
i = '.01' if not i else '.' + str(int(i.strip('.')) + 1).zfill(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment