Python Forum
Rename multiple photos with DateTimeOriginal timestamp - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Rename multiple photos with DateTimeOriginal timestamp (/thread-38497.html)



Rename multiple photos with DateTimeOriginal timestamp - Stjude1982 - Oct-20-2022

Hi,

I'm still very much in the learning phase of creating python programs.

At present, I'm trying to sort Google Photos onto PC but going forwards I'm hoping script can be used to sort a photo dump from mobile phone.
Ideally, the script would unzip photo downloads, however, I'm happy doing this manually until I get first part of script running.
The unzipped files have contained following extensions '.jpg', '.jpeg', '.JPG'.

One script that seen suggests passing through lower() - I'd be happy if I can get script running for '.JPG' for time being.

The files I'm dealing with just now seem to be of format DSC_*.JPG. I'd like to iterate the files in the Downloads directory and rename in 'DateTimeOriginal'.jpg format.

I've read a few examples of programs and created following script:

from pathlib import Path
from PIL import Image
from PIL.ExifTags import TAGS
import os

#define function to retrieve exif table data
def get_exif(file_data):
    ret = {}
    i = Image.open(file_data)
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret

#iterate over Downloads directory
for filename in Path("/home/stjude1982/Downloads").glob("*.jpg"):
    exif = get_exif(filename)
    #check if file contains exif data
    if "DateTimeOriginal" in exif:
        source = filename
        destination = Path(filename).with_name(datetime.strptime(exif["DateTimeOriginal"], "%Y:%m:%d %H:%M:%S"))
        os.rename(source, destination)
        print(destination)
    else:
        print(f"[WARNING] {filename}: no EXIF header")
This program is generating the following error, however, given my lack of experience/knowledge I'm pretty sure there's more wrong with the program than error suggested. Can anyone help, please? I seem to be going round in circles.

Error:
%Run RenameGooglePhotos.py Traceback (most recent call last): File "/home/stjude1982/Python/RenameGooglePhotos.py", line 21, in <module> destination = Path(filename).with_name(datetime.strptime(exif["DateTimeOriginal"], "%Y:%m:%d %H:%M:%S")) NameError: name 'datetime' is not defined
FYI - I started off reading and copying the following and edited to the above:

https://linuxtut.com/en/4b042473f8442da9989a/

Regards,

Stephen


RE: Rename multiple photos with DateTimeOriginal timestamp - Larz60+ - Oct-20-2022

add at top of script:
from datetime import datetime


RE: Rename multiple photos with DateTimeOriginal timestamp - Pedroski55 - Oct-21-2022

Perhaps this will help you to see what's going on step by step.

Copy and paste each line one by one into your Python IDE, to see what it is doing.

Of course, the if ... else: has to be pasted in one go.

Then, when you understand what's happening, put lines 25 to 35 in a function and return newname.

I replaced the gaps in the new file names with underscore, because, if I had hundreds or thousands of photos to work on, I would do this in bash, and bash doesn't like the spaces!

Probably a good idea to standardize all the names to .jpg or whatever first.

from PIL import Image
from PIL.ExifTags import TAGS
from pathlib import Path
from datetime import datetime

path2img = '/home/pedro/Downloads/'
file1 = path2img + '1666308164309.jpg' # from my phone
file2 = path2img + '1646613137056.jpg' # from my phone
file3 = path2img + 'Athena.jpg' # no exif data

im1 = Image.open(file1)
exif1 = im1._getexif()
# seems like the key you want is 36867       
for key in exif1.keys():
    print(key, exif[key])
newname = exif2[36867].replace(' ', '_')
print(newname)

# try again with file2
im2 = Image.open(file2)
exif2 = im2._getexif()
newname = exif2[36867].replace(' ', '_')
print(newname)

# try again with file3, no exif data
im3 = Image.open(file3)
# returns None when no exif data
exif3 = im3._getexif()
# if no exif data give the time now as name
if exif3 == None:
    print('Problem: no exif data')
    now = datetime.now()
    newname = now.strftime("%A %d-%b-%Y %H:%M:%S").replace(' ', '_')
else:
    newname = exif3[36867].replace(' ', '_')
print(newname)