首页 > 解决方案 > 类 datetime.time 不能转换为 pandas 中的日期时间

问题描述

我是来自 R 背景的 Python 新手,我在 pandas 中有以下时间栏

   time
   09:12:23
   09:34:33
   10:23:22
   11:23:33

我想把它转换成熊猫的时间对象,我在 python 中做以下

     df['time'] = pd.to_datetime(df['time']).dt.time

为什么它向我显示以下错误。

   class datetime.time is not convertible to datetime

标签: pythonpandas

解决方案


如果可能,相同的非日期时间/时间值添加参数errors='coerce'

print (df)
       time
0     aaaaa
1  09:34:33
2  10:23:22
3  11:23:33

df['time'] = pd.to_datetime(df['time'], errors='coerce').dt.time
print (df)
       time
0       NaT
1  09:34:33
2  10:23:22
3  11:23:33

编辑:检查这个值:

print (df[pd.to_datetime(df['time'], errors='coerce').isnull()])
    time
0  sdass

编辑1:

可以通过以下方式转换为 timedeltas to_timedelta- 优点是使用 pandas timedelta函数,该函数不适用于times:

df['time'] = pd.to_timedelta(df['time'], errors='coerce')
print (df)
      time
0      NaT
1 09:34:33
2 10:23:22
3 11:23:33

推荐阅读