0

I am trying to extract "DateTimeOriginal" metadata from an image in MM/DD/YYYY HH:MM format, But it isn't working. I tried different approaches but none of them seem to work.

1. Extracting "Date Taken" using ExifTool

            try:
                exiftool_process = subprocess.Popen(
                    ['exiftool', '-DateTimeOriginal', '-s3', '-n', file_path],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.DEVNULL,
                    universal_newlines=True
                )
                date_taken = exiftool_process.communicate()[0].strip()
                if date_taken:
                    metadata_values["Date Taken"] = date_taken
            except (subprocess.CalledProcessError, FileNotFoundError):
                pass

Now, I want to format the obtained value to MM/DD/YYYY HH:MM. Below are the functions defined to obtain the required format.

Approach 1:

def format_date_taken(date_taken):
    try:
        datetime_obj = datetime.datetime.strptime(date_taken, "%Y:%m:%d %H:%M:%S")
        return datetime_obj.strftime("%m/%d/%Y %H:%M")
    except ValueError:
        try:
            datetime_obj = datetime.datetime.strptime(date_taken, "%Y:%m:%d %H:%M:%S%z")
            return datetime_obj.strftime("%m/%d/%Y %H:%M")
        except ValueError:
            return date_taken.split(" ")[0]

Approach 2:

def format_date_taken(date_taken):
    try:
        if "-" in date_taken:
            # To handle date format with time offset (e.g., 2023:05:14 15:53:13-04:00)
            date_str, time_offset = date_taken.split("-")
            datetime_obj = datetime.datetime.strptime(date_str, "%Y:%m:%d %H:%M:%S")
            formatted_date = datetime_obj.strftime("%m/%d/%Y")
            return f"{formatted_date} {time_offset[:6]}"
        else:
            # To handle date format without time offset (e.g., 2020:12:31 19:31:49)
            datetime_obj = datetime.datetime.strptime(date_taken, "%Y:%m:%d %H:%M:%S")
            return datetime_obj.strftime("%m/%d/%Y %H:%M")
    except ValueError:
        return date_taken.split(" ")[0]

Approach 3:

def format_date_taken(date_taken):
    if "-" in date_taken:
        # Handle date format with time offset (e.g., 2023:05:14 15:53:13-04:00)
        date_str = date_taken.split("-")[0]
    else:
        # Handle date format without time offset (e.g., 2020:12:31 19:31:49)
        date_str = date_taken
    
    date_parts = date_str.split(":")
    
    # Extract the year, month, day, hour, and minute based on their positions
    year = date_parts[0]
    month = date_parts[1]
    day = date_parts[2]
    hour = date_parts[3].split()[0].split()[0]
    minute = date_parts[3].split()[1]
    
    # Return the values as a formatted string
    return f"{month}/{day}/{year} {hour}:{minute}"

it will convert the value to a string and extract the year, month, day, hour, and minute based on their positions.

But none of these approaches are working. However, a 3rd party application like PIE is able to retrieve the value in MM/DD/YYYY HH:MM format. Help me!

Kulasangar
  • 9,046
  • 5
  • 51
  • 82
VeeyesPlus
  • 57
  • 6

1 Answers1

0

Why not use exiftool's built in -d (-dateFormat) option?

On the command line you would use

exiftool -DateTimeOriginal -s3 -d "%m/%d/%Y %H:%M" /path/to/files/

But take note that the -d option is incompatible with the -n (--printConv) option in your original listing.

See ExifTool Common Date Format Codes for full list of % codes.

To add a further option, the -n option can be applied to individual tags by appending a # to the name. For example, if you needed the Duration of a video in seconds but still needed to format the date, you could use

exiftool -DateTimeOriginal -Duration# -s3 -d "%m/%d/%Y %H:%M" /path/to/files/

You would then get the DateTimeOriginal as a formatted time stamp, but Duration would return the raw number.

StarGeek
  • 4,948
  • 2
  • 19
  • 30
  • Additional comment, if you are processing a lot of files, you do not want to call exiftool once for each file. Exiftool's biggest performance hit is the startup time and calling it once for each file will significantly increase the processing time. See [ExifTool Common Mistake #3](https://exiftool.org/mistakes.html#M3). A better solution is to use a wrapper such as [PyExifTool](https://github.com/sylikc/pyexiftool) which uses the [`-stay_open` option](https://exiftool.org/exiftool_pod.html#stay_open-FLAG) to keep exiftool running in the background. – StarGeek Jun 14 '23 at 21:27