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?

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Any idea how to drop the invalid values as I convert them?
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 stackoverflow.com/questions/19522990/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.