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

使用Pandas筛选Excel时间列报错:仅可对类datetime值用.dt访问器

解决Pandas筛选Excel时间段时的AttributeError: Can only use .dt accessor with datetimelike values错误

你的代码尝试筛选Excel中指定时间段的数据,但报错核心原因是**ingezameldop列未被识别为datetime类型**,Pandas的.dt访问器仅支持datetime64类型的列。以下是具体解决方法:

原代码及报错

原代码

import pandas as pd
from datetime import datetime
from datetime import date

dagStart = datetime.strptime(str(date.today())+' 06:00:00', '%Y-%m-%d %H:%M:%S')
dagEind = datetime.strptime(str(date.today())+' 23:00:00', '%Y-%m-%d %H:%M:%S')

data = pd.read_excel('inzamelbestand.xlsx', index_col=9) 

data = data.loc[data['ingezameldop'].dt.time.between(dagStart.time(), dagEind.time())]

data.to_excel("oefenexcel.xlsx")

报错信息

Traceback (most recent call last):
  File "C:\Users\Inzamelhelden\orden.py", line 10, in <module>
    data = data.loc[data['ingezameldop'].dt.time.between(dagStart.time(), dagEind.time())]
  File "C:\Users\Inzamelhelden\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\generic.py", line 5907, in __getattr__
    return object.__getattribute__(self, name)
  File "C:\Users\Inzamelhelden\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\accessor.py", line 183, in __get__
    accessor_obj = self._accessor(obj)
  File "C:\Users\Inzamelhelden\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\accessors.py", line 513, in __new__
    raise AttributeError("Can only use .dt accessor with datetimelike values")
AttributeError: Can only use .dt accessor with datetimelike values. Did you mean: 'at'?

解决步骤

方法1:读取Excel时直接解析日期列

在pd.read_excel中使用parse_dates参数,指定需要解析为datetime类型的列(这里是ingezameldop):

import pandas as pd
from datetime import datetime, date

# 更优雅的方式组合日期和时间
dagStart = datetime.combine(date.today(), datetime.strptime("06:00:00", "%H:%M:%S").time())
dagEind = datetime.combine(date.today(), datetime.strptime("23:00:00", "%H:%M:%S").time())

# 读取时直接解析目标列为datetime类型
data = pd.read_excel('inzamelbestand.xlsx', index_col=9, parse_dates=['ingezameldop'])

# 执行筛选
data = data.loc[data['ingezameldop'].dt.time.between(dagStart.time(), dagEind.time())]

data.to_excel("oefenexcel.xlsx")

方法2:读取后转换列为datetime类型

如果无法在读取时确定列格式,可在读取后用pd.to_datetime转换,同时处理无法转换的异常值:

import pandas as pd
from datetime import datetime, date

dagStart = datetime.combine(date.today(), datetime.strptime("06:00:00", "%H:%M:%S").time())
dagEind = datetime.combine(date.today(), datetime.strptime("23:00:00", "%H:%M:%S").time())

data = pd.read_excel('inzamelbestand.xlsx', index_col=9) 

# 转换目标列为datetime类型,errors='coerce'将无效值转为NaT
data['ingezameldop'] = pd.to_datetime(data['ingezameldop'], errors='coerce')
# 删除包含NaT的行(可选,避免后续筛选出错)
data = data.dropna(subset=['ingezameldop'])

# 执行筛选
data = data.loc[data['ingezameldop'].dt.time.between(dagStart.time(), dagEind.time())]

data.to_excel("oefenexcel.xlsx")

额外说明

  • 如果ingezameldop列仅包含时间(无日期),转换为datetime类型后仍可正常提取时间部分进行筛选。
  • 使用datetime.combine替代字符串拼接,能避免不必要的类型转换问题,代码更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:57:16