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

如何基于datetime列筛选当前时间到10小时前的pandas DataFrame数据

问题解决方法

报错TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'的核心原因是main_table['dateTime']列当前为字符串格式,未转换为pandas支持的datetime64时间类型,无法直接和datetime对象进行算术运算与对比。

正确实现步骤

  1. 先将dateTime列转换为时间类型
import pandas as pd
import datetime

# 转换dateTime列为datetime类型,errors='coerce'会将非法格式的时间转为空值NaT,可按需添加
main_table['dateTime'] = pd.to_datetime(main_table['dateTime'])
  1. 计算10小时前的时间阈值,组合两个筛选条件过滤数据
# 计算10小时前的时间节点
time_cutoff = datetime.datetime.today() - pd.Timedelta(hours=10)
# 同时满足时间在10小时内、weeks>80两个条件
filtered_df = main_table[(main_table['dateTime'] >= time_cutoff) & (main_table['weeks'] > 80)]

补充说明

如果需要严格限定时间范围为「10小时前到当前时间」,避免数据中存在未来时间的干扰,可以补充上限条件:

now = datetime.datetime.today()
time_cutoff = now - pd.Timedelta(hours=10)
filtered_df = main_table[(main_table['dateTime'] >= time_cutoff) & (main_table['dateTime'] <= now) & (main_table['weeks'] > 80)]

内容的提问来源于stack exchange,提问作者V.Nouri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:45:03