Created
February 17, 2025 05:39
-
-
Save dk949/7d52f0417947ce958d3314a34364693e to your computer and use it in GitHub Desktop.
A small script to fix the datetime of jpg files in a directory. It copies the exif datetime to the file's mtime and vice versa. This can fix various importing issues with photo management software (e.g. Google photos).
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
""" | |
A small script to fix the datetime of jpg files in a directory. | |
It copies the exif datetime to the file's mtime and vice versa. | |
This can fix various importing issues with photo management software (e.g. Google photos). | |
NOTE: This script uses the piexif library to read and write exif data, you will need to install it. | |
NOTE 2: This script will overwrite the mtime of the files. If you use the | |
`--no-exif-to-mtime` mtime WILL BE SET TO THE CURRENT TIME!! | |
""" | |
import piexif | |
from datetime import datetime | |
from pathlib import Path | |
import argparse | |
import os | |
parser = argparse.ArgumentParser() | |
parser.add_argument("dir", type=Path) | |
parser.add_argument("--no-exif-to-mtime", dest="exif_to_mtime", action="store_false") | |
parser.add_argument("--no-mtime-to-exif", dest="mtime_to_exif", action="store_false") | |
parser.add_argument("-q", "--quiet", action="store_true") | |
args = parser.parse_args() | |
dir = args.dir | |
for file in dir.iterdir(): | |
if file.suffix.lower() != ".jpg": | |
continue | |
if not args.quiet: | |
print("processing ", str(file), " ... ", sep="", end="") | |
if args.mtime_to_exif: | |
stat = file.stat() | |
date = datetime.fromtimestamp(stat.st_mtime) | |
d = piexif.load(str(file)) | |
new_date = date.strftime("%Y:%m:%d %H:%M:%S").encode("utf-8") | |
d["Exif"][piexif.ExifIFD.DateTimeOriginal] = new_date | |
d["Exif"][piexif.ExifIFD.DateTimeDigitized] = new_date | |
piexif.insert(piexif.dump(d), str(file)) | |
if args.exif_to_mtime: | |
d = piexif.load(str(file)) | |
exif_date = datetime.strptime( | |
d["Exif"][piexif.ExifIFD.DateTimeOriginal].decode("utf-8"), | |
"%Y:%m:%d %H:%M:%S", | |
) | |
os.utime(file, (exif_date.timestamp(), exif_date.timestamp())) | |
if not args.quiet: | |
print("done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment