Member-only story
[Python] How to get EXIF from a file
10 min readSep 19, 2019
目標
- 開啟檔案
- 取得EXIF的Date Time等資料
- 把檔案名稱根據EXIF的時間日期更改成固定格式
取得EXIF
在網上找了一下,決定使用PIL這個package. 這是個外加的package,所以需要另外安裝.
pip install Pillow
開啟檔案以及取得EXIF的資料,用以下範例碼可以做到
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGSdef process_file():
# open the file
i_file = Image.open('P2019_0917_17384450.jpg') # test file
# Get EXIF
exif_info = i_file._getexif()
for tag, val in exif_info.items():
key = TAGS.get(tag)
# GPSInfo has sub-level of data
if key == "GPSInfo":
for t in val:
sub_decoded = GPSTAGS.get(t, t)
print(f'[{tag}] {sub_decoded}: {val[t]}')
print(f'[{tag}] {key}: {val}')
if __name__ == '__main__':
process_file()
取得DateTime以及轉換
從EXIF tags可以取得數個不同的Datetime,至少可以取得兩個參數:
- DateTimeOriginal
- DateTimeDigitized
這裡我取用DateTimeDigitized這一個參數,它的格式如下:
2019:09:17 17:38:44
# yyyy:mm:dd hh:mm:ss
GPS裡面有兩個參數跟時間有關:
- GPSDateStamp
- GPSTimeStamp
GPSTimeStamp很麻煩,因為它的格式是turple而不是單純的integer.所以必須先轉換成integer然後再當成timestamp轉換成時間
GPSTimeStamp: ((21, 1), (38, 1)…