0

I am trying to change the data type of a column from object to date in pandas dataframe. I cannot control the data type with dtypes because both the string(text) and date data are of object type. (I shouldn't use Try Except). Can I find out if the selected column contains string values ​​without using Try Except?

0

2 Answers 2

1

Pandas's to_datetime() has an errors argument. You can set it to 'coerce', for instance, to turn bad dates into NaT.

df = pd.DataFrame({'t': ['20200101', '2020-01-01', 'foobar', '2020-01-01T12:17:00.333']})
pd.to_datetime(df['t'], errors='coerce')

# out:
0   2020-01-01 00:00:00.000
1   2020-01-01 00:00:00.000
2                       NaT
3   2020-01-01 12:17:00.333
Name: t, dtype: datetime64[ns]
Sign up to request clarification or add additional context in comments.

1 Comment

I knew this parameter. I wanted no convert in that column if there is a string value, so I wanted to check it. Thank you for the answer I can use that too.
1

Try this to convert object to datetime

df[col] = pd.to_datetime(df[col], errors='coerce')

1 Comment

I knew this parameter. I wanted no convert in that column if there is a string value, so I wanted to check it. Thank you for the answer I can use that too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.