You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas筛选指定日期后数据报错:str与datetime无法比较

解决Pandas日期比较时的TypeError问题

问题背景

你有如下结构的数据集:

reference     country         date                   title     author  is_gov  text
0   r901128a_BOA    australia   1990-11-28 00:00:00     A Proper Role for Monetary Policy   fraser  0   They would no doubt argue that to have two obj...
1   r911003a_BOA    australia   1991-10-03 00:00:00         fraser  0   Today I wish to talk about real interest rates...

你想要筛选出日期在2016年1月1日及之后的数据,编写了如下代码:

import pandas as pd
import datetime as dt
df = pd.read_excel(r"C:...",parse_dates=['date'])
df1 = df[['reference','country','date','title','author','is_gov','text']].copy()
  

start = dt.datetime(2016,1,1)
df1 = df1[df1['date']>=start]
df1

但运行时触发了错误:

TypeError: '>=' not supported between instances of 'str' and 'datetime.datetime'

错误原因

这个错误的核心是:虽然你在read_excel里指定了parse_dates=['date'],但Pandas并没有成功将date列转换为datetime类型——该列仍然是字符串(object类型)。当你尝试用字符串和datetime.datetime对象做比较时,就会抛出这个类型不兼容的错误。

解决方案

我们需要确保date列被正确转换为datetime类型,这里有两种可靠的处理方式:

方式一:强制显式转换日期列

在读取数据后,主动用pd.to_datetime转换date列,确保类型正确:

import pandas as pd
import datetime as dt

# 读取数据
df = pd.read_excel(r"C:...", parse_dates=['date'])
# 显式转换date列为datetime类型,errors='coerce'会把无法解析的日期转为NaT(缺失值)
df['date'] = pd.to_datetime(df['date'], errors='coerce')

# 复制需要的列
df1 = df[['reference','country','date','title','author','is_gov','text']].copy()

# 筛选2016-01-01及之后的数据
start = dt.datetime(2016,1,1)
df1 = df1[df1['date'] >= start]
# 可选:删除日期无效的行(如果有NaT)
df1 = df1.dropna(subset=['date'])
df1

方式二:读取时确保解析生效

如果parse_dates没生效,可能是Excel里的日期存储格式特殊,可以尝试指定读取引擎,或者更明确地配置解析参数:

# 用openpyxl引擎读取(如果是.xlsx文件),并确保parse_dates生效
df = pd.read_excel(r"C:...", parse_dates=['date'], engine='openpyxl')

验证方法

在转换后,可以用以下代码检查date列的类型,确认是否为datetime64[ns]:

print(df['date'].dtype)

如果输出是datetime64[ns],说明转换成功,此时再进行日期比较就不会报错了。

内容的提问来源于stack exchange,提问作者Kash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:50:29