Reputation: 521
How I convert the df to pandas datetime datatype? (with null value)
datet = pd.DataFrame(['2018-09-07 00:00:00','2017-09-15 00:00:00',''],columns=['Mycol'])
datet['Mycol'] = datet['Mycol'].apply(lambda x:
dt.datetime.strptime(x,'%Y-%m-%d %H:%M:%S'))
But it returns error: ValueError: time data '' does not match format '%Y-%m-%d %H:%M:%S'
How can I resolve that error? (keep the null as blank)
Thanks!
Upvotes: 5
Views: 13896
Reputation: 1726
Just do:
datet['Mycol'] = pd.to_datetime(datet['Mycol'], errors='coerce')
This will automatically convert the null to an NaT
value.
Output:
0 2018-09-07
1 2017-09-15
2 NaT
Upvotes: 11
Reputation: 374
Its because your third column contains an empty string. Remove that and it works. It cant convert the empty string with the match format.
datet = pd.DataFrame(['2018-09-07 00:00:00','2017-09-15 00:00:00'],columns=['Mycol'])
datet['Mycol'] = datet['Mycol'].apply(lambda x: datetime.datetime.strptime(x,'%Y-%m-%d %H:%M:%S'))
Upvotes: 0