2018年11月5日 星期一

用 Python 修正相片日期


上星期參加了 WTIA 舉辦的「2018 北台灣物聯網投資合作商機考察參訪團」。帶了相機及手機拍攝活動相片。回到香港,才發現相機在 8 月到名古屋時調快了一小時,於是編寫以下 Python 程式,讀取相片中的 EXIF 資料,把所有 Canon 拍攝的相片日期都調慢一小時,變回正確時間。
##----------------------------------------------------------------------------------------
##  Fix Photo Creation Date
##----------------------------------------------------------------------------------------
##  Platform: macOS Mojave + Python 2.7
##  Copyrights Pacess Studio, 2018.  All rights reserved.
##----------------------------------------------------------------------------------------

import os
import time
import exifread

##----------------------------------------------------------------------------------------
##  Global variables
_path = "./"

##----------------------------------------------------------------------------------------
##  Get files from directory
for root, dirs, files in os.walk(_path):

   for file in files:
   
      if file.startswith("."):
         continue

      if not file.endswith(".JPG"):
         continue

      print("\nProcessing "+file+"...", end="")

      ##----------------------------------------------------------------------------------------
      ##  Get EXIF
      handle = open(_path+file, "rb")
      tags = exifread.process_file(handle)
   
      machine = str(tags["Image Make"])
      print(machine, end="")

      ##  Process only if "Canon"
      if "Canon" not in machine:
         continue

      ##----------------------------------------------------------------------------------------
      ##  Subtract one hour
      #datetime = os.path.getmtime(file)
      #timeString = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(datetime))
      timeString = str(tags["Image DateTime"])
      datetime = time.mktime(time.strptime(timeString, "%Y:%m:%d %H:%M:%S"))

      newDatetime = datetime-(60*60)
      newTimeString = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(newDatetime))
      
      os.utime(_path+file, (newDatetime, newDatetime))
      print(" ("+timeString+" => GMT:"+newTimeString+")", end="")

print("\nDone\n")

沒有留言: