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

pandas如何筛选带时区和不带时区的所有datetime类型列

解决方案

目前有两种兼容性较好的通用筛选方法,不需要逐个枚举时区类型:

方法1:使用pandas类型判断工具(全版本兼容)

该方法是最稳妥的实现,is_datetime64_any_dtype会自动识别所有带时区/不带时区的日期时间类型:

from pandas.api.types import is_datetime64_any_dtype

dt_cols = [col for col in df.columns if is_datetime64_any_dtype(df[col])]

方法2:select_dtypes 通用匹配(pandas 1.1+ 支持)

新版本pandas已经支持直接用datetime作为通用类型参数,一次性匹配所有日期时间列:

dt_cols = df.select_dtypes(include=["datetime"]).columns

原写法失效原因说明

带时区的日期时间类型是pandas的扩展数据类型,不属于numpy原生的np.datetime64类型,因此直接传入np.datetime64或datetime64作为筛选条件时,只能匹配到不带时区的原生日期时间列。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:36:07