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

DataFrame带时区datetime64[ns]索引与Timestamp比较报错问题

解决带时区Datetime索引与Timestamp的比较问题

问题场景

使用yfinance获取标普500日线数据后,尝试用时间戳筛选索引时触发类型不匹配错误:

Invalid comparison between dtype=datetime64[ns, TIMEZONE] and Timestamp

输入代码:

import yfinance as yf
import pandas as pd
import datetime as dt

x = yf.Ticker('^GSPC').history(period='max',interval='1d').loc[:,['Open']]
stdate = pd.Timestamp(2015,12,31)
edate = dt.datetime.today()

y = x.index > stdate

原因分析

yfinance返回的DataFrame索引为**带时区的datetime64[ns, America/New_York]**类型,而手动创建的stdate是无时区的Timestamp,两者无法直接进行比较运算。

两种可行解决方法

方法1:给比较时间戳添加匹配时区

提取索引的时区信息,将筛选用的时间戳转换为同时区类型:

# 获取索引的时区属性
tz = x.index.tz
# 给起始、结束时间添加对应时区
stdate = pd.Timestamp(2015,12,31, tz=tz)
edate = pd.Timestamp(dt.datetime.today(), tz=tz)

# 生成目标掩码
mask = (x.index > stdate) & (x.index < edate)

方法2:移除索引的时区信息

将带时区的索引转换为无时区的datetime类型,直接与普通Timestamp比较:

# 移除索引的时区标记
x.index = x.index.tz_localize(None)
# 生成目标掩码
mask = (x.index > stdate) & (x.index < edate)

验证结果

运行任意一种方法后,mask会返回符合预期的布尔数组:

[False, False, False, True, True... True]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:55:15