I can get the EXIF data from an image using PIL, but how can I get the date and time that the photo was taken?
ExifTags.TAGS is a mapping from tag to tag name. You can use it to create a map of tag names to values.
On this particular picture, there are a few different "date" properties (DateTime, DateTimeOriginal, DateTimeDigitized) that could be used.
import json
from PIL import Image, ExifTags
from datetime import datetime
def main(filename):
image_exif = Image.open(filename)._getexif()
if image_exif:
# Make a map with tag names
exif = { ExifTags.TAGS[k]: v for k, v in image_exif.items() if k in ExifTags.TAGS and type(v) is not bytes }
print(json.dumps(exif, indent=4))
# Grab the date
date_obj = datetime.strptime(exif['DateTimeOriginal'], '%Y:%m:%d %H:%M:%S')
print(date_obj)
else:
print('Unable to get date from exif for %s' % filename)
Output:
{
"DateTimeOriginal": "2008:11:15 19:36:24",
"DateTimeDigitized": "2008:11:15 19:36:24",
"ColorSpace": 1,
"ExifImageWidth": 3088,
"SceneCaptureType": 0,
"ExifImageHeight": 2320,
"SubjectDistanceRange": 2,
"ImageDescription": " ",
"Make": "Hewlett-Packard ",
"Model": "HP Photosmart R740 ",
"Orientation": 1,
"DateTime": "2008:11:15 19:36:24",
...
}
2008-11-15 19:36:24