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

Python datetime调用to_period报错 如何获取无时间的季度末日期

报错根因

to_period()是pandas时间类型(Timestamp/DateTimeIndex)的专属方法,Python标准库自带的datetime.datetime对象没有这个方法,直接调用就会触发你看到的AttributeError。另外原逻辑里end_time返回的是季度末最后一天的23:59:59.999999999,带纳秒级时间戳,不符合去除时间部分的要求。同时原代码里先把日期转字符串再用strptime解析的步骤属于冗余操作,datetime.date.today()本身返回的就是不带时分秒的纯日期对象,不需要反复做格式转换。

可直接运行的改进代码

方案1:沿用pandas逻辑(代码最简洁)

和你原本的写法逻辑完全一致,只修正类型问题和时间残留问题:

import pandas as pd
import datetime

# 转成pandas的Timestamp类型,支持to_period方法
today = pd.Timestamp(datetime.date.today())
# 取季度末时间后调用.date()直接剥离时间部分,得到纯日期
quarter_end_date = today.to_period("Q").end_time.date()

df['Qend'] = quarter_end_date

返回结果为标准datetime.date类型,无任何时分秒字段,例如当日为2024年5月20日时,返回值为datetime.date(2024, 6, 30)。

方案2:纯Python标准库实现(无pandas依赖)

不需要依赖pandas时间API,计算效率更高,自动适配跨年、闰年、大小月等所有边界场景:

import datetime
import math

today = datetime.date.today()
# 计算当前日期所属季度
current_quarter = math.ceil(today.month / 3)
# 计算季度结束后下一个月的年份、月份
if current_quarter == 4:
    next_month = 1
    next_year = today.year + 1
else:
    next_month = current_quarter * 3 + 1
    next_year = today.year
# 取下一个月1号往前偏移1天,即为当前季度最后一天
quarter_end_date = datetime.date(next_year, next_month, 1) - datetime.timedelta(days=1)

df['Qend'] = quarter_end_date

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 11:06:19