TypeError: ufunc subtract cannot use operands with types dtype('O') and dtype('M8[ns]')

446 阅读1分钟

Pandas 处理两列时间,想求时间差,在做差时报错如下:

TypeError: ufunc subtract cannot use operands with types dtype('O') and dtype('<M8[ns]')

bug 解释:

1. 

'b'       boolean
'i'       (signed) integer
'u'       unsigned integer
'f'       floating-point
'c'       complex-floating point
'O'       (Python) objects
'S', 'a'  (byte-)string
'U'       Unicode
'V'       raw data (void)

2. dtype('<M8[ns]') 是表示时间的数据类型。

解决办法:

将两列都变为 pandas 中日期的标准类型:

df['after'] = pd.to_datetime(df['after'],format = '%Y-%m-%d %H:%M:%S')

即把 after 字段变成 标准日期格式。

 

问题解决。