Last active
May 5, 2020 09:40
-
-
Save urklc/82f00ff8c3bb2cc8aa7fb48d3d02f81e to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python | |
import PIL | |
from PIL import Image, ExifTags | |
import argparse | |
import os | |
import shutil | |
import subprocess | |
exifcmd = "/usr/local/bin/exiftool" | |
def main(args): | |
for full_path in args.filenames: | |
path, fn = os.path.split(full_path) | |
img = Image.open(full_path) | |
img_exif = img.getexif() | |
if img_exif is None: | |
print("Sorry, image has no exif data.") | |
else: | |
img_exif_dict = dict(img_exif) | |
for key, date_taken in img_exif_dict.items(): | |
if key in ExifTags.TAGS: | |
if (ExifTags.TAGS[key] == 'DateTime'): | |
head, tail = os.path.split(full_path) | |
filename, file_extension = os.path.splitext(full_path) | |
date_parts = date_taken.split() | |
day = date_parts[-2] | |
hour = date_parts[-1] | |
if hour.startswith("24"): | |
hour = "00" + hour[2:] | |
new_filename = day + "_" + hour + file_extension | |
new_filename = new_filename.replace(":", "-").replace(" ", "_") | |
new_path = os.path.join(head, new_filename) | |
# Checks that there is not a file already. | |
while os.path.exists(new_path): | |
pieces = new_path.split(".") | |
pieces[-2] += '_b' | |
new_path = ".".join(pieces) | |
print("Renaming: %s -> %s" % (full_path, new_path)) | |
shutil.move(full_path, new_path) | |
# Done for this file | |
break | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('filenames', type=str, default=None, | |
nargs="*", help="Files to rename") | |
args = parser.parse_args() | |
main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment