Search code examples
python-3.xstrptimetry-except

Try-Except: sre_constants.error


I have to validate some dates imported from a file, the dates have different formats. For example %Y/%m/%d and %d/%m/%Y. The problem is that I have to reformat them to be able to divide them by eachother etc.

I have found out that I need to use Try/Except, but when I use the following code (where dates[1] is all the dates):

UPDATE:

I'm trying a different code to change the wrong formats with strptime and strftime. But, I dont know if its a good way to use strptime/strftime in except? Is except only meant to be for prints etc?

The code:

for dates in data_from_file:
  dates = (dates[1])
  print(dates)
  try:
    validate_format = datetime.datetime.strptime(dates, '%d/%m/%Y')
  except ValueError:
    datetime.datetime.strptime(dates, '%Y/%m/%d').strftime('%d/%m/%Y')
  except ValueError:
    datetime.datetime.strptime(dates, '%d. %B %Y').strftime('%d/%m/%Y')

The first except ValueError works, since I see the format of the time data *format* does not match '%d/%m/%Y' error changes. There is three different formats, so I have to change the last one too. But it seems like it remembers the formats from the first except ValueError?

Now it says: ValueError: time data '%d. %B %Y' (in numbers, ofc) does not match format '%Y/%m/%d'


Solution

  • Finished result:

    for line in data_file:
     line = (line.decode('utf-8').strip())
     if line.startswith('#'):
      pass
     else:
      names, birthdates, residences, genders = line.split('#')
      try:
       datetime.strptime(birthdates, '%d/%m/%Y')
      except:
       try:
         bad_format = birthdates
         birthdates = datetime.strptime(bad_format, '%Y/%m/%d').strftime('%d/%m/%Y')
       except ValueError:
         bad_format_letters = birthdates
         if bad_format_letters in bad_format_letters:
           birthdates = datetime.strptime(bad_format_letters, '%d. %B %Y').strftime('%d/%m/%Y')
      nameslist.append(names)
      birthdateslist.append(birthdates)
      residenceslist.append(residences)
      genderslist.append(genders)