Now that I've figured out How do I strtotime in python? I'm wondering if there's a more elegant way to handle entries with empty dates, which return an error if I try to strptime() them.
warrant_issued = cells[4].get_text().strip()
try:
warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y')
except:
warrant_issued_no = ''
This works, but I'm parsing four or five dates in each row and it seems both wordy and repetitive. I'm thinking I should define a function, but are there other ways I should make this more pythonic?
For brevity, I did from datetime import datetime
at the outset so datetime.strptime()
works. Otherwise I'd need datetime.datetime.strptime()
I think that defining a function and catching only exceptions that you know how to handle is precisely the way to do this.
def parse_datetime(warrant_issued):
try:
warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y')
except ValueError:
warrant_issued_no = ''
warrants_issued = [ parse_datetime(cell.get_text().strip()) for cell in cells ]