Skip to content

Commit

Permalink
Date parsing improvements and extra tests
Browse files Browse the repository at this point in the history
  • Loading branch information
damianmoore committed Aug 8, 2021
1 parent d62e9bd commit cce5220
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
17 changes: 13 additions & 4 deletions photonix/photos/utils/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,19 @@ def get_datetime(path):
'''
# TODO: Use 'GPS Date/Time' if available as it's more accurate

# First try the date in the metadate
# First try the date in the metadata
metadata = PhotoMetadata(path)
date_str = metadata.get('Date/Time Original')
if date_str:
return parse_datetime(date_str)
parsed_datetime = parse_datetime(date_str)
if parsed_datetime:
return parsed_datetime

date_str = metadata.get('Create Date')
if date_str:
return parse_datetime(date_str)
parsed_datetime = parse_datetime(date_str)
if parsed_datetime:
return parsed_datetime

# If there was not date metadata, try to infer it from filename
fn = os.path.split(path)[1]
Expand All @@ -93,7 +97,12 @@ def get_datetime(path):
if matched:
date_str = '{}-{}-{}'.format(matched.group(1), matched.group(3), matched.group(4))
return datetime.strptime(date_str, '%Y-%m-%d')
return None

# Otherwise get file creation time
try:
return datetime.fromtimestamp(os.stat(path).st_ctime).replace(tzinfo=utc)
except:
return None


def get_dimensions(path):
Expand Down
4 changes: 3 additions & 1 deletion tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@ def test_datetime():
parsed_datetime = get_datetime(photo_path)
assert parsed_datetime.isoformat() == '2010-06-03T00:00:00'

# Date is parseable but has slashes instead of colons
photo_path = str(Path(__file__).parent / 'photos' / 'bad_date.jpg')
parsed_datetime = get_datetime(photo_path)
assert parsed_datetime.year == 2000
assert parsed_datetime.isoformat() == '2000-01-01T00:00:00+00:00'

# Some of the date digits are the letter X so fall back to file creation date
photo_path = str(Path(__file__).parent / 'photos' / 'unreadable_date.jpg')
parsed_datetime = get_datetime(photo_path)
assert parsed_datetime == None
assert parsed_datetime.isoformat() == '2021-08-08T21:11:25.231271+00:00'

0 comments on commit cce5220

Please sign in to comment.