Skip to content

Instantly share code, notes, and snippets.

@CameronHall
Last active May 22, 2021 12:30
Show Gist options
  • Save CameronHall/38fd8bc352dd807ea2a3d534e4676873 to your computer and use it in GitHub Desktop.
Save CameronHall/38fd8bc352dd807ea2a3d534e4676873 to your computer and use it in GitHub Desktop.
Photo Date Fixer
import piexif
import os
from shutil import copyfile
from datetime import datetime
def get_diff(path_name, alleged_date):
alleged_date = datetime.strptime(alleged_date, '%Y:%m:%d %H:%M:%S')
exif_dict = piexif.load(path_name)
exif_date = exif_dict['0th'][piexif.ImageIFD.DateTime].decode('ascii')
created = datetime.strptime(exif_date, '%Y:%m:%d %H:%M:%S')
return alleged_date - created
def change_exif(path_name, diff):
exif_dict = piexif.load(path_name)
exif_date = exif_dict['0th'][piexif.ImageIFD.DateTime].decode('ascii')
created = datetime.strptime(exif_date, '%Y:%m:%d %H:%M:%S')
new_date_obj = created + diff
new_date = new_date_obj.strftime("%Y:%m:%d %H:%M:%S").encode('ascii')
exif_dict['0th'][piexif.ImageIFD.DateTime] = new_date
exif_dict['Exif'][piexif.ExifIFD.DateTimeOriginal] = new_date
exif_dict['Exif'][piexif.ExifIFD.DateTimeDigitized] = new_date
exif_dict['1st'][piexif.ImageIFD.DateTime] = new_date
exif_bytes = piexif.dump(exif_dict)
piexif.insert(exif_bytes, path_name)
return new_date_obj.timestamp()
def backdate_file(path_name, timestamp):
""" Copy file so we get a new create date.
This is because we can't set the date of "st_birthtime"
into the future, but we can backdate it.
"""
dest_path = path_name.replace('Source', 'Updated')
copyfile(path_name, dest_path)
os.utime(dest_path, times=(timestamp, timestamp))
def get_files_in_folder(path, extension):
files = []
for r, d, f in os.walk(path):
for file in f:
if extension in file:
files.append(os.path.join(r, file))
return files
def fix_dates(directory, sample_name, alleged_date_for_sample):
sample_path = directory + sample_name
diff = get_diff(sample_path, alleged_date_for_sample)
files = get_files_in_folder(directory, ".JPG")
for file in files:
timestamp = change_exif(file, diff)
backdate_file(file, timestamp)
directory = "~/Documents/Date Fixer/Source/"
sample_name = "DSC08089.JPG"
alleged_date_for_sample = "2019:12:27 15:37:00"
fix_dates(directory, sample_name, alleged_date_for_sample)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment