Search code examples
pythonrjpegimage-file

How to append "Date" or "Date taken" to a JPEG image file's name?


Here's an example of what my .jpg files look like:

screenshot of list of image files

I want to append either the "Date" or "Date taken" info — not the "Date created" or "Date modified" info. I saw this answer but I think it would only do the latter. Also, I would like the date formatted as YYYYMMDD or YYYY-MM-DD, no times included. Can someone please help? I know enough python to run a script but definitely not enough to actually write or troubleshoot one. :\

If anyone knows how to do this in R, I'm much more comfortable there.


Solution

  • If I have understood your request correctly, please find below a proposed solution to your problem using the packages exifr and stringr. With some adaptations for your specific case (i.e. file extension and path diretory), it should work.

    library(exifr)
    library(stringr)
    
    # Retrieve all images with extension .jpg from your working directory 
    # (the file extension and possibly the file path must be adapted to your case)
    files <- list.files(path = getwd(), pattern = "*.jpg")
    
    # Read images Exif metadata
    dat <- read_exif(files)
    
    # Retrieve file names and info about dates from Exif metadata
    dat[ ,c(grep(pattern = "^FileName", names(dat)), grep(pattern = "Date", names(dat)))]
    
    # Choose the desired date (here, I chose the "FileModifyDate" column which corresponds to the dates the images were taken - i.e. column #2)
    chosenDate <- dat[ ,c(grep(pattern = "^FileName", names(dat)), grep(pattern = "Date", names(dat)))][,2]
    
    
    # Append file names with dates 
    # (Do not forget to change the file extension in paste0() according to your case - here the extension is ".jpg") 
    file.rename(files, 
                paste0(file_path_sans_ext(files),"_", 
                       gsub(":","-",sapply(chosenDate, stringr::str_extract, ".*(?= )")),
                       ".jpg"))