On 2019-12-18 18:12, Tobiah wrote:
What I tried is a cascade of try's:

try:
   d = strptime(date_string, format_string_1)
except:
   try:
     d = strptime(date_string, format_string_2)
   except:
     try:
       d = strptime(date_string, format_string_3)
     except:
       ...


This is not about dates, but for the above, I'd try:

      for f in (format1, format2, format3):
          try:
              d = strptime(date_string, f)
          except:
              continue
          else:
              break

That way you can manipulate the content and number
of the formats, or pull them from a database or whatever
without having to edit your code in a messy way.

A couple of point about your code:

1. Don't use a bare 'except' because it'll catch _any_ exception. See what exception strptime will raise and catch only that.

2. Why use 'continue' instead of 'pass'?
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to