Python Forum
Problems with getting image's DateTimeOriginal
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problems with getting image's DateTimeOriginal
#1
I am making an image sorting program based on the date which the image was taken in which everything works perfectly except one thing. I know my code is very messy, but this is my first ever large program. I will post just a small part of it and try to explain. So, first of all, it tries to get all the image's properties using a previously defined function. It works fine and returns a dictionary of all the properties. If an error occurs, that filename is appended to a list called cant_sort. After that, it tries to get the date in which the image was taken. Not all the pictures have this, so if a KeyError occurs, it tries to get the last modification date. The rest of the code doesn't matter for my question. The problem is that most of the files which don't have the date in which image was taken, slip into the cant_sort list. But I want them to go into thesort_by_mod dictionary. I am thinking that I should arrange the try and except statements differently. I want to note, that everything else works perfectly and there are no other errors. Also if I should post the full code in order to locate the problem, I can do that. Thanks in advance.
import shutil

def get_date(fn):
    ret = {}
    i = Image.open(fn)
    info = i.getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret

for file in images:

    try:
        all_data = get_date(file)
        try:
            taken_date = all_data['DateTimeOriginal'].replace(" ", ":")
            taken_date = taken_date.split(":")
            list_dates = list(taken_date[0:3])
            if str(list_dates) not in existing_dates:
                existing_dates[str(list(taken_date[0:3]))] = file
            if str(list_dates) in existing_dates:
                if file not in existing_dates[str(list_dates)].split(","):
                    existing_dates[str(list_dates)] = (existing_dates[str(list_dates)] + "," + file)
        except KeyError:
            mod_date = all_data['DateTime'].replace(" ", ":")
            mod_date = mod_date.split(":")
            list_dates = list(mod_date[0:3])
            if str(list_dates) not in sort_by_mod:
                sort_by_mod["m"+str(list(mod_date[0:3]))] = file
            if str(list_dates) in sort_by_mod:
                if file not in sort_by_mod[str(list_dates)].split(","):
                    sort_by_mod[str(list_dates)] = (sort_by_mod[str(list_dates)] + "," + file)
    except:
        cant_sort.append(file)
Reply
#2
There are date operations that allow many date manipulations including comparisons.
I'd like to suggest running this tutorial: https://pymotw.com/3/datetime/
Reply
#3
I found the problem. Usually, image name is 2 numbers separated with an underscore, like, 12345_12345, but those files which are written like IMG-1248215-WA0001 don't get sorted properly. I can simply fix this by renaming them. But can anyone please explain why do these files are randomly called differently?
Reply
#4
Just make this one function to get the date for all cases.

import os
import datetime

from PIL import Image

 
def get_date(fn):
    img = Image.open(fn)
    # 306 is the date?
    exif_date = img.getexif().get(306)
    try:
        date = datetime.datetime.strptime(exif_date, '%Y:%m:%d %H:%M:%S')
    except (TypeError, ValueError):
        date = datetime.datetime.fromtimestamp(os.stat(fn).st_mtime)
    return date
More information about the Tags: https://www.vcode.no/web/resource.nsf/ii2lnug/642.htm
Tag 306 is the creation DateTime of the image.
If the tag does not exist, the get Function returns None.
In this case the strptime Method causes a TypeError.
If the Value of the Tag 306 is not in the right format, it throws an ValueError.
If one of these exceptions occurs, the mtime of the file is taken.

This function should always return a valid Date.
This will make the rest easier.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Rename multiple photos with DateTimeOriginal timestamp Stjude1982 2 1,156 Oct-21-2022, 12:24 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