Last active
December 22, 2015 04:29
-
-
Save Perlence/6417641 to your computer and use it in GitHub Desktop.
Rename JPEG images with EXIF data according to date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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