Skip to content

Instantly share code, notes, and snippets.

@bijai
Created May 16, 2021 14:03
Show Gist options
  • Save bijai/3e5d1dbb1527d929a710dca23f18171d to your computer and use it in GitHub Desktop.
Save bijai/3e5d1dbb1527d929a710dca23f18171d to your computer and use it in GitHub Desktop.
Python script to set image taken time exif from file name
from datetime import datetime
import piexif
import pathlib
import os
def parseDateFromImageName(p_fName,p_time):
#Sample format IMG-20150515-WA0003
splitted = p_fName.split('-')
dateOnly = datetime.strptime(splitted[1], '%Y%m%d')
return dateOnly.replace(hour=p_time.hour,minute=p_time.minute,tzinfo=p_time.tzinfo)
def setImageTaken(filename):
try:
exif_dict = piexif.load(filename)
fname = pathlib.Path(filename)
#Modified time from file attribute
mtime = datetime.fromtimestamp(fname.stat().st_mtime)
new_date = parseDateFromImageName(filename,mtime).strftime("%Y:%m:%d %H:%M:%S")
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_bytes = piexif.dump(exif_dict)
piexif.insert(exif_bytes, filename)
except piexif._exceptions.InvalidImageDataError as e:
print(f'{filename} - Not JPG')
except Exception as e:
print(f'{filename} - Error - {e}')
else:
print(filename)
if __name__ == '__main__':
for (root,dirs,files) in os.walk('WhatsApp Images', topdown=True):
for file in files:
setImageTaken(os.path.join(root,file))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment