Index ¦ Archives ¦ RSS

Sorting photos by date using exif date info

Estimated read time: 2 minutes

For a family event I received photos from about 6 persons, and wanted to view all of them, sorted by date. The problem was that the timestamps of the files were sometimes incorrect, and also in all but one cases the exif timestamp was incorrect as well (but at least that was consistently incorrect, e.g. all behind of time by 20 mins, etc.)

So first I searched for a photo where a clock is shown, then matched photos by different authors showing the same action to know the time delta of each camera. The rest can be scripted: just read the exif info, apply the necessary time correction based on the camera model, and touch the file with the correct date. Then any image viewer can show the photos, sorted by date.

Here is the script I came up with:

for i in *.jpg
    # 2012:01:01 01:01:01 -> 2012-01-01 01:01:01
    date=$(exiv2 $i |grep timestamp|sed 's/.* : //'|sed 's/^\([0-9][0-9][0-9][0-9]\):\([0-9][0-9]\):\([0-9][0-9]\)/\1-\2-\3/')
    # date string -> epoch
    unix=$(date --date="$date" +%s)

    model=$(exiv2 $i |grep model|sed 's/.*: //')

    if [ "$model" == "NIKON D40" ]; then
        unix=$(($unix-1320)) # Alice
        unix=$(($unix+3600)) # Bob

    # epoch -> date string
    date=$(python -c "import time; print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime($unix))")
    # profit!
    touch --date="$date" $i
# write back the timestamps to the exif info (thx boobaa)
jhead -dsft *.jpg

And additionally if you don’t want to mess up the settings of the image viewer, you can use:

c=0; for i in $(ls -lhtr *.jpg|sed 's/.* //'); do c=$((c+1)); cp -a $i new/$(printf "%03d" $c).jpg; done

to order filenames based on the file timestamp.

© Miklos Vajna. Built using Pelican. Theme by Giulio Fidente on github.