Classify images by date in Python

2016-08-13 - Arnaud Duforat

I need to sort a large amount of images by date. The idea would be to group the images into folders by day of taking the photo.

Python seems to me perfect for doing this, so let's start by recovering the metadata of the images. As explained on http://www.blog.pythonlibrary.org/2010/03/28/getting-photo-metadata-exif-using-python the Python Imaging Library allows to do it quite simply as follows:

from PIL import Image
from PIL.ExifTags import TAGS
 
def get_exif(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

This returns many fields including the one we are interested in: DateTime.

Now to list the paths of all the images to be able to use this method, we will use the too little known global method of the standard library (see : https://docs.python.org/2/library/glob.html).

By combining all this, we obtain the source code that you will find on https://github.com/neokeld/image-classification/blob/master/sort-image-by-day/sortImagesByDay.py