0

I want to convert a column to type date time. Some of the date are invalid, and I want to get rid of them. Here's what I have right now

df_event['event_date'] = try: pd.to_datetime(df_event['event_date']) except ValueError as e: pass

It says this is invalid syntax. What would be the correct syntax here? Moreover, for this piece of code, I'm trying to convert first, then I'll drop the rows where the value is not date time. Is there a way to drop the invalid rows direcrly in one step?

Tianhe Xie
  • 261
  • 1
  • 10

1 Answers1

2

You should move the assignment operation inside your try block and the syntax error should go away. Also, I'm not sure if writing the whole code in single line would work for an indentation strict language like Python.

try: 
    df_event['event_date'] = pd.to_datetime(df_event['event_date']) 
except ValueError as e: 
    pass
  • Any idea how to drop the invalid values as I convert them? – Tianhe Xie Oct 25 '20 at 01:38
  • You could put the try block in a loop that iterates over each of the dates. In the try block, you could use the date after a successful conversion. If the conversion fails, the value won't be used and you could move on to the next iteration. Adding a similar question for reference https://stackoverflow.com/questions/19522990/python-catch-exception-and-continue-try-block – stunner.agk Oct 25 '20 at 01:59