[Tutor] (no subject)

Mats Wichmann mats at wichmann.us
Sat Mar 23 18:41:47 EDT 2019


On 3/23/19 3:16 AM, Peter Otten wrote:

> Personally I would use a try...except clause because with that you can 
> handle invalid dates like 99999999_etc.xls gracefully. So
> 
> ERASED = "erased_"
> 
> 
> def strip_prefix(name):
>     if name.startswith(ERASED):
>         name = name[len(ERASED):]
>     return name
> 
> 
> def extract_date(name):
>     datestr = strip_prefix(name)[:8]
>     return datetime.datetime.strptime(datestr, DATEFMT).date()
> 
> 
> for name in ...:
>     try:
>         file_date = extract_date(name)
>     except ValueError:
>         pass
>     else:
>         print(file_date)

I'd endorse this approach as well.. with a DATEFMT of "%Y%m%d", you will
get a ValueError for every date string that is not a valid date... which
you then just ignore (the "pass"), since that's what you wanted to do.



More information about the Tutor mailing list