I have the catchily-named Sony Ericsson Xperia X10 Mini Pro smartphone. The device runs a customised version of Android that Sony Ericsson developed to make better use of the unusually small screen size. Among the customised apps is a photo album which displays all the pictures taken with the device's camera, ordered by date and grouped into months.

One annoyance I've found with this app, however, is the way the photo ordering is achieved. For whatever reason, the developers chose to use the file creation time time provided by the file system to determine the order in which to display them. This works fine until you start moving the files around. In my case, I had backed them up to my PC, formatted the SD card and moved them back - which of course reset all the creation times and put the photos out of order.

As you might expect, though, the time the photo was actually taken is stored in the file's metadata. This data, which the developers probably should have used in the first place, can be extracted with a quick Python script:


#!/usr/bin/env python2

import Image
from ExifTags import TAGS
import os
import time
import sys

# Must be invoked with file argument
if len(sys.argv) < 2:
    sys.exit("Usage: %s file" % sys.argv[0])

# Load the file
path = sys.argv[1]
im = Image.open(path)

# Extract image time from exif info
exif = im._getexif()
if exif is None: sys.exit("Exif tags not found")

exif = dict([ (TAGS.get(tagid,tagid),value) for tagid,value in exif.items() ])

if "DateTime" not in exif: sys.exit("DateTime not found")
imgtime = int(time.mktime(time.strptime( exif["DateTime"], "%Y:%m:%d %H:%M:%S" )))

# Set last accessed and modified times on file
os.utime(path,(imgtime,imgtime))

print "Set %s to %s" % (path,time.strftime("%c",time.localtime(imgtime)))

This script uses the PIL imaging library to load a given JPEG file, extract the date from the Exif metadata, and finally update the file's creation and last-modified times with this date. Credit goes to Mike Driscoll for the tag extraction code.

I was then able to correct my photo times by mounting the SD card and running the script on each file like so:


$ find . -name '*.jpg' -exec fixalbumtime '{}' \;

Triumph!