Last active
July 24, 2020 22:48
-
-
Save joaquinco/1fe25b346ff5472c4dad9b1e18dda675 to your computer and use it in GitHub Desktop.
Python script to set modifiy date of images files to the one specified in exif metadata
This file contains hidden or 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
""" | |
Python script to set modifiy date of images files to the one specified in exif metadata. | |
Usage: | |
python applyexifdate.py Photos/**/*.jpg | |
""" | |
import argparse | |
from datetime import datetime | |
import logging | |
import os | |
import sys | |
import time | |
# pip install exif | |
from exif import Image | |
def get_exif_date(img_file): | |
""" | |
Return exif date. Appearantly it's stored in format YYYY:MM:DD HH:MM:SS. | |
""" | |
img = Image(img_file) | |
if not img.has_exif: | |
return None | |
timestamp = None | |
for key in ['datetime', 'datetime_original']: | |
if hasattr(img, key): | |
timestamp = getattr(img, key) | |
break | |
if not timestamp and hasattr(img, 'gps_timestamp') and hasattr(img, 'gps_datestamp'): | |
hour = ':'.join(img.gps_timestamp) | |
timestamp = f'{img.gps_datestamp} {hour}' | |
if not timestamp: | |
return | |
timestamp_format = '%Y:%m:%d %H:%M:%S' | |
return datetime.strptime(timestamp, timestamp_format) | |
def parse_args(args): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('files', nargs='+') | |
parser.add_argument('-l', '--log-level', choices=['info', 'debug'], default='info') | |
return parser.parse_args(args) | |
def main(): | |
args = parse_args(sys.argv[1:]) | |
logging.basicConfig( | |
level=getattr(logging, args.log_level.upper()), | |
format='%(asctime)s %(message)s', | |
) | |
all_count = 0 | |
processed_count = 0 | |
for image_path in args.files: | |
all_count += 1 | |
with open(image_path, 'rb') as img_file: | |
modified_date = get_exif_date(img_file) | |
if not modified_date: | |
continue | |
logging.debug(f'{image_path} {modified_date}') | |
timestamp = time.mktime(modified_date.timetuple()) | |
os.utime(image_path, (os.path.getatime(image_path), timestamp)) | |
processed_count += 1 | |
logging.info(f'Processed {processed_count} out of {all_count}') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment