image_sorting/mtime2exifcreatedate.sh

47 lines
2.4 KiB
Bash
Executable File

#!/usr/bin/bash
# This shell script is used to set the EXIF CreateDate tag from the file's timestamp (the modified date).
# Please note that the changes applied cannot be undone.
# As changing exif data of an image is itself an action causing a change in modification timestamp (mtime),
# this script manipulates this timestamp via the touch command.
#
# It uses python3 and it's core libraries and the linux commands exiftool and touch.
# I could not find any easy (shell) tool to convert from a given date format to another one, so I used python
# and it's built-in libraries to solve the problem. (strptime and strftime!)
#
# April 2024, Benjamin Burkhardt (last modified: Apr 20, 20:54 2024)
# list the directory with find; remove . (the directory itself) by grepping ./ and iterate over every item in the list
find . -print | grep ./ | while read filename; do
MDATE=$(date -r $filename)
echo "--- STARTING '$filename' OVERWRITING (with $MDATE as modification date) ---"
EXIFDATE=$(python3 -c "
import datetime, locale
locale.setlocale(locale.LC_TIME, '') # set locale to system default
ctime = datetime.datetime.strptime(\"$MDATE\", \"%a %d. %b %H:%M:%S %Z %Y\") # get ctime and convert it to an datetime.datetime object
print(ctime.strftime(\"%Y:%m:%d %H:%M:%S\"))
"); # Get the ctime (last change time) of the file 'filename' and convert it to the format 'YYYY:mm:dd HH:MM:SS' (for exiftool)
echo "exiftool -CreateDate=\"$EXIFDATE\" \"$filename\" | grep error (Now changing CreateDate EXIF arg of '$filename' to $EXIFDATE)";
exiftool -CreateDate="$EXIFDATE" "$filename" | grep error;
TOUCHDATE=$(python3 -c "
import datetime, locale
locale.setlocale(locale.LC_TIME, '') # set locale to system default
ctime = datetime.datetime.strptime(\"$MDATE\", \"%a %d. %b %H:%M:%S %Z %Y\") # get ctime and convert it to an datetime.datetime object
print(ctime.strftime(\"%Y%m%d%H%M.%S\"))
"); # Get the ctime (last change time) of the file 'filename' and convert it to the format 'YYYYmmddHHMM.ss' (for touch command)
echo "touch -c -m -t \"$TOUCHDATE\" \"$filename\" (Resetting modify time of '$filename' (as it changed while exif writing))";
touch -c -m -t "$TOUCHDATE" "$filename"; # -c for not create new files; -m for changing the modify date; -t for timestamp
echo "rm "$filename"_original (removing exiftool's traces :)";
rm "$filename"_original;
echo # for better readability of the output
done