我认为您需要errors='coerce'
将非日期时间转换为NaT
in 的参数to_datetime
:
df['date_time'] = pd.to_datetime(df['date_time'], errors='coerce')
然后如果需要NaT
使用 use删除所有行dropna
:
df = df.dropna(subset=['date_time'])
样本:
a = ["2016-05-19 08:25:00","2016-05-19 16:00:00","2016-05-20 07:45:00",
"2016-05-24 12:50:00","2016-05-25 23:00:00","aaa"]
df = pd.DataFrame({'date_time':a})
print (df)
date_time
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00
2 2016-05-20 07:45:00
3 2016-05-24 12:50:00
4 2016-05-25 23:00:00
5 aaa
df['date_time'] = pd.to_datetime(df['date_time'], errors='coerce')
print (df)
date_time
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00
2 2016-05-20 07:45:00
3 2016-05-24 12:50:00
4 2016-05-25 23:00:00
5 NaT
df = df.dropna(subset=['date_time'])
print (df)
date_time
0 2016-05-19 08:25:00
1 2016-05-19 16:00:00
2 2016-05-20 07:45:00
3 2016-05-24 12:50:00
4 2016-05-25 23:00:00