如何将具有空值的列转换为日期时间格式?

Boo*_*aka 1 python datetime type-conversion pandas

如何将df转换为pandas datetime数据类型?(具有空值)

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'))
Run Code Online (Sandbox Code Playgroud)

但是它返回错误:ValueError:time data''与格式'%Y-%m-%d%H:%M:%S'不匹配

我该如何解决该错误?(将null保留为空白)

谢谢!

Vis*_*hur 5

做就是了:

datet['Mycol'] = pd.to_datetime(datet['Mycol'], errors='coerce')
Run Code Online (Sandbox Code Playgroud)

这将自动将null转换为NaT值。

输出:

0   2018-09-07
1   2017-09-15
2          NaT
Run Code Online (Sandbox Code Playgroud)