类 datetime.time 不能转换为 pandas 中的日期时间

Nei*_*eil 8 python pandas

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

   time
   09:12:23
   09:34:33
   10:23:22
   11:23:33
Run Code Online (Sandbox Code Playgroud)

我想将其转换为 pandas 的时间对象,我正在 python 中执行以下操作

     df['time'] = pd.to_datetime(df['time']).dt.time
Run Code Online (Sandbox Code Playgroud)

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

   class datetime.time is not convertible to datetime
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

如果可能,相同的非日期时间/时间值添加参数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
Run Code Online (Sandbox Code Playgroud)

编辑:检查此值:

print (df[pd.to_datetime(df['time'], errors='coerce').isnull()])
    time
0  sdass
Run Code Online (Sandbox Code Playgroud)

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