Search code examples
pythoncsvpython-2.6valueerror

ValueError: time data 'LEGACY SYSTEM' does not match format '%H:%M:%S'


I see this is a popular question, so hopefully someone can help me out. I, however, am stumped. I have CSV file that contains a timestamp in the first column, such as

18:49:45
19:50:31
20:51:26

My code is below. I think I am using the proper formatting for 24-hours, minutes, and seconds.

  import csv
  import time

  with open('file.csv', 'rb')as csvfile:
      filereader = csv.reader(csvfile, delimiter=',')
      for row in filereader:
          date = row[0]
          parsed = datetime.datetime.strptime(date, '%H:%M:%S')

Error: ValueError: time data 'LEGACY SYSTEM' does not match format '%H:%M:%S'


Solution

  • You have a header row. You can use next to retrieve (and then discard) the first line from your csv.reader iterator:

    from datetime import datetime
    import csv
    from io import StringIO
    
    file = StringIO("""LEGACY SYSTEM
    18:49:45
    19:50:31
    20:51:26""")
    
    # replace file with open('file.csv', 'rb')
    with file as csvfile:
        filereader = csv.reader(csvfile, delimiter=',')
        next(filereader)
        for row in filereader:
            parsed = datetime.strptime(row[0], '%H:%M:%S')
            print(parsed)
    
    # 1900-01-01 18:49:45
    # 1900-01-01 19:50:31
    # 1900-01-01 20:51:26
    

    If you have multiple, say two, header rows, you can use a for loop to ignore them:

    for _ in range(2):
        next(filereader)