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?
Asked
Active
Viewed 513 times
2 Answers
1
Try this to convert object
to datetime
df[col] = pd.to_datetime(df[col], errors='coerce')

Ajay A
- 1,030
- 1
- 7
- 19
-
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. – uckocaman Dec 09 '20 at 12:58
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]

Pierre D
- 24,012
- 7
- 60
- 96
-
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. – uckocaman Dec 09 '20 at 12:58