0

I have a list of strings and I want to drop items that are not a date. I simply want to check if they are a date, not convert them to datetime. I am using dateutil.parser - how can I handle the error it raises and continue the loop? Here is my code:

from dateutil.parser import parse

def drop_nondates(dates, fuzzy=False):
    for string in dates:
        try: 
            parse(string, fuzzy=fuzzy)
        except:
            dates.remove(string)
            pass
            
    return dates

Testing on small list:

In: drop_nondates( ['January 2018', 'Enero 2018', 'not a date 2018', '2018'] )
>>> ['January 2018', 'not a date 2018', '2018'] 

but desired output would be:

['January 2018', '2018'] 
tonystark
  • 3
  • 1
  • 4
  • 1
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Asocia Jun 20 '20 at 15:29
  • Don't remove elements from your iterable while iterating. That's the problem of your code. – Asocia Jun 20 '20 at 15:30
  • @Asocia, it does, thank you! I spent too much time looking for ways to handle the error and didn't look for ways around it. – tonystark Jun 20 '20 at 15:47

1 Answers1

0

see Asocia's comment: don't modify a list while iterating over it. Your code works fine if you e.g. append all "parseable" results to a new list and return that:

from dateutil.parser import parse

def drop_nondates(dates, fuzzy=False):
    result = []
    for string in dates:
        try: 
            parse(string, fuzzy=fuzzy)
        except:
            pass
        else:
            result.append(string)
          
    return result

drop_nondates( ['January 2018', 'Enero 2018', 'not a date 2018', '2018'] )
# ['January 2018', '2018']
FObersteiner
  • 22,500
  • 8
  • 42
  • 72