String to Datetime onject in DataFrame while ignore empty strings

Viewed 461

I have a column date in a DataFrame, it is either empty or have a string in this format '2021-06-04T15:14:30.512Z' I want to convert this to Datetime object but not sure how to handle the empty columns. I want to keep them empty or null but convert the rest. I tried to use this to convert string to datetime

from dateutil import parser
a = '2021-06-04T15:14:30.512Z'
datetime.fromisoformat(a)

But unable to use this across dataframe column while ignoring the empty string. Can someone please help me? Thanks

1 Answers
import pandas as pd

try with errors='coerce' parameter in to_datetime() method:

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

If you want only date part:

df['date']=pd.to_datetime(df['date'],errors='coerce').dt.date
Related