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

如何从pandas datetime对象中提取日期?.dt.date失效怎么办

问题根因

.dt.date调用失效的原因很简单:

  • 你给pd.to_datetime()传入的是单个时间字符串,此时返回值是单个pandas.Timestamp标量对象,不是序列类型
  • .dt访问器是专门给存储时间类型的Series、DatetimeIndex这类序列对象用的,单个Timestamp没有这个属性,调用自然报错。
对应解决方案

根据你处理的对象类型,选对应方法即可:

场景1:处理单个Timestamp标量(即你当前代码返回的对象类型)

不需要加.dt前缀,直接调用对象自带的方法即可:

  • 要得到Python原生datetime.date类型的日期值:
import pandas as pd
ts = pd.to_datetime('2022-06-12 00:00:00', infer_datetime_format = True)
date_res = ts.date()
print(date_res)  # 输出:2022-06-12
  • 要保留pandas原生时间类型(后续做时间序列运算更方便,不会丢失类型兼容性),用normalize()方法将时间部分重置为当日0点,等价于仅保留日期维度:
date_res_pd = ts.normalize()
  • 如果需要得到固定格式的日期字符串,直接用strftime格式化:
date_str_res = ts.strftime('%Y-%m-%d')  # 输出字符串'2022-06-12'

场景2:处理存储多个时间值的pandas Series

这时候才需要用.dt访问器调用对应方法:

# 构造示例时间Series
time_series = pd.Series(pd.to_datetime(['2022-06-12 00:00:00', '2023-09-15 14:23:00']))
# 1. 得到Python原生date组成的Series
date_series_native = time_series.dt.date
# 2. 得到保留pandas datetime64类型的日期Series(时间部分归0,推荐用于后续计算)
date_series_pd = time_series.dt.normalize()
# 3. 得到格式化日期字符串组成的Series
date_str_series = time_series.dt.strftime('%Y-%m-%d')

补充说明:infer_datetime_format参数在新版pandas中已经废弃,传入单个标准格式的时间字符串时不需要加这个参数,不会影响解析结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 15:09:21