#!/usr/bin/env python

"""exifrename.py: Rename a JPEG to the date and time the image was taken in YYYYMMDDHHMMSSxx.jpg format"""

__author__ = 'Mike Maraya'
__copyright__ = 'Copyright (c) 2014, Mike Maraya'
__license__ = 'MIT'
__version__ = '1.0'
__email__ = 'mike.maraya@gmail.com'
__status__ = 'Development'
__maintainer__ = 'Mike Maraya'

import exifread, glob, os.path, sys, time

for pattern in (sys.argv[1:]):
    for old_filename in glob.glob(pattern):
        f = open(old_filename, 'rb')
        dir = os.path.dirname(os.path.abspath(old_filename)) + os.sep
        tags = exifread.process_file(f, details=False)
        if tags.has_key('EXIF DateTimeOriginal'):
            exif_date = tags['EXIF DateTimeOriginal']
        file_date = time.strptime(str(exif_date), "%Y:%m:%d %H:%M:%S")
        if tags.has_key('EXIF SubSecTime'):
            sub_sec = tags['EXIF SubSecTime']
            counter = int(str(sub_sec))
        else:
            counter = 0
        new_filename = dir + time.strftime('%Y%m%d%H%M%S', file_date) + str(counter).zfill(3) + '.jpg'
        while os.path.isfile(new_filename):
            counter += 1
            new_filename = dir + time.strftime('%Y%m%d%H%M%S', file_date) + str(counter).zfill(3) + '.jpg'
        os.rename(os.path.abspath(old_filename), os.path.abspath(new_filename))
        print 'Renamed %s to %s' % (old_filename, new_filename)
        f.close()

@@ -503,69 +503,40 @@
     
-dir = os.path.dirname(os.path.abspath(old_filename)) + os.sep
+# get EXIF date or use file date
 %0A   
@@ -587,16 +587,58 @@
 =False)%0A
+        exif_date = '1900:01:01 00:00:00'%0A
         
@@ -816,71 +816,90 @@
     
-if tags.has_key('
+# get 
 EXIF 
-SubSecTime'):%0A            sub_sec = tags%5B
+sub-second time or use 000%0A        counter = 0%0A        if tags.has_key(
 'EXI
@@ -911,17 +911,18 @@
 SecTime'
-%5D
+):
 %0A       
@@ -948,55 +948,125 @@
 str(
-sub_sec))%0A        else:%0A            counter = 0
+tags%5B'EXIF SubSecTime'%5D))%0A        # rename file%0A        dir = os.path.dirname(os.path.abspath(old_filename)) + os.sep
 %0A   

use 1900-01-01 if EXIF DateTimeOriginal not present