You need to enable JavaScript to run this app. Python datetime时间差计算如何无异常获取年月(不足取0)
优惠活动
大模型
产品
解决方案
定价
更多

Python datetime时间差计算如何无异常获取年月(不足取0)

核心报错原因

两个datetime对象直接做减法,返回的是datetime.timedelta类型的固定时长差值对象。该类型仅支持访问days、seconds、microseconds这类基于固定长度的属性,不存在和历法相关的year、month属性,因此直接访问对应属性会触发AttributeError。

需求实现逻辑

全程无需异常捕获,通过固定条件分支计算即可满足要求:

  • 先通过比较大小统一两个时间的先后顺序,避免出现负差值
  • 计算两个时间的总间隔天数,若小于30天,直接输出年、月差值为0
  • 若间隔超过30天,基于两个时间的自然年月日属性,计算自然年、月的真实差值:
    • 先计算基础年差、月差
    • 若结束时间的日期小于开始时间的日期,说明未达整月,月差值扣减1
    • 若扣减后月差值小于0,说明未达整年,年差值扣减1,月差值补12
可直接运行的代码示例
from datetime import datetime

# 两个输入时间点
t_late = datetime(2020, 9, 8, 19, 42, 39, 264658)
t_early = datetime.fromtimestamp(1598192097.728026)
# 固定将早的时间设为start,晚的设为end,规避计算负值
start, end = sorted([t_late, t_early])

total_interval_days = (end - start).days
if total_interval_days < 30:
    diff_year = 0
    diff_month = 0
else:
    diff_year = end.year - start.year
    diff_month = end.month - start.month
    # 结束时间的日期早于开始时间,说明尚未达到整月间隔,扣减月数
    if end.day < start.day:
        diff_month -= 1
    # 月差为负说明尚未达到整年间隔,调整年、月计数
    if diff_month < 0:
        diff_year -= 1
        diff_month += 12

# 输出计算结果
print(f"时间差为{diff_year}年{diff_month}月")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 16:24:04