pythonimageexiftoolmetadata-extractorpiexif

Trying to extract "DateTimeOriginal" metadata from an image in MM/DD/YYYY HH:MM format


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!


Solution

  • 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.