Search code examples
pythoncsvdatetimestrptimestrftime

Python ValueError: time data '' does not match format '%m/%d/%Y'


I have the following error:

line 73, in formatFile outRow.append(datetime.datetime.strptime(row[5],'%m/%d/%Y').strftime('%Y-%m-%d')) ValueError: time data '' does not match format '%m/%d/%Y'

Script below:

import datetime

  def formatFile(fname):
    print(fname)

       formattedFile=open(workingFolder() + '\\FormattedFile.csv','w')
       writer = csv.writer(formattedFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL,lineterminator='\n')
       writer.writerow(["Name","Unit","Unit Size","Other","Note","Mode Here"])

       with open(fName) as f:
          reader=csv.reader(f,delimiter=',')    
          next(reader)
          for row in reader:
              outRow=[]


              outRow.append(datetime.datetime.strptime(row[5],'%m/%d/%Y').strftime('%Y-%m-%d'))

              #other script here that works well as part of a for loop

              print(outRow)
              writer.writerow(outRow)

The date I have is in a .csv file as a text looks like this: "11/19/2017" I want it in this format: "2017-11-19". Not sure what I am doing wrong?

I have read this about 5 times and still unsure why it is giving me the error: https://docs.python.org/2/library/datetime.html

Example of csv file here:

"Name","Unit","Unit Size","Other","Mode","Date" 
"name here","unit here","YYY x YY","Note","Mode here","11/19/2017"
"name here","unit here","YYY x YY","Note","Mode here","11/20/2017"
"name here","unit here","YYY x YY","Note","Mode here","12/04/2017"

Solution

  • There was a total row at the bottom of the list which was crashing the file... Corrected with this:

    for row in reader:
        if "Total" not in row:
           #script here
        else:
            break