strptime for different languages

Tobiah toby at tobiah.org
Wed Dec 18 13:12:53 EST 2019


> 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.


Tobiah




More information about the Python-list mailing list