Python Forum
Rename multiple photos with DateTimeOriginal timestamp
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rename multiple photos with DateTimeOriginal timestamp
#1
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
Larz60+ write Oct-20-2022, 11:23 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use BBCode tags rather than attachment on future posts. Thank you

Attached Files

.py   RenameGooglePhotos.py (Size: 815 bytes / Downloads: 95)
Reply
#2
add at top of script:
from datetime import datetime
Reply
#3
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  error in timestamp Led_Zeppelin 3 3,270 Jun-15-2022, 08:28 PM
Last Post: deanhystad
  error in timestamp Led_Zeppelin 0 1,021 Jun-10-2022, 07:59 PM
Last Post: Led_Zeppelin
  Rename part of filename in multiple files atomxkai 7 7,428 Feb-18-2022, 10:03 PM
Last Post: atomxkai
Photo Moving 2 photos from each subfolder to another folder Blacklonewolf 1 2,078 Oct-28-2021, 04:07 PM
Last Post: DeaD_EyE
  Rename Multiple files in directory to remove special characters nyawadasi 9 6,510 Feb-16-2021, 09:49 PM
Last Post: BashBedlam
  Copy mp3 file multiple times and rename Mar10 4 3,782 Sep-23-2020, 01:09 AM
Last Post: Mar10
  Problems with getting image's DateTimeOriginal Pythenx 3 2,902 May-02-2019, 02:21 PM
Last Post: DeaD_EyE
  Timestamp is undefined ErnestTBass 7 8,004 Feb-16-2019, 08:27 PM
Last Post: snippsat
  Download multiple images and rename them andie31 4 5,160 Sep-13-2018, 10:26 AM
Last Post: andie31
  inserting photos in 1 sheet of a 6 sheet excel file fails Pedroski55 0 2,393 Mar-03-2018, 01:53 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020