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

使用datetime计算日期差报错:传入1触发日期越界ValueError

日期计算报错修复方案

问题描述

调用dates函数传入参数1时,先输出“41 days, 0:00:00”,随后抛出异常:

Traceback (most recent call last):
File "", line 22, in
print(dates(i))
^^^^^^^^
File "", line 18, in dates
SD = date(YY2, MM2, DD2)
^^^^^^^^^^^^^^^^^^^
ValueError: day is out of range for month

传入参数0时可正常得到结果,日期数据取自a0.txt文件,原代码如下:

from datetime import *

f = open('a0.txt')
n = f.readlines()

def dates(j):
    l = n[j]
    nl = list(l)
    nl.remove('\n')
    nl.remove('\t') #these were used because origianal txt file inlcuded tabulation
    DD1 = int(nl[0] + nl[1])
    MM1 = int(nl[3] + nl[4])
    YY1 = int(nl[6] + nl[7] + nl[8] + nl[9])
    DD2 = int(nl[10] + nl[10])
    MM2 = int(nl[13] + nl[14])
    YY2 = int(nl[16] + nl[17] + nl[18] + nl[19]) #day, month, year for each date
    FD = date(YY1, MM1, DD1)
    SD = date(YY2, MM2, DD2)
    delta = abs(SD - FD) #difference
    return delta
for i in range(len(n)): #difference for each line of dates
    print(dates(i))

错误原因

  1. 制表符处理不彻底:nl.remove('\t')仅移除列表中第一个制表符,每行剩余的制表符会打乱字符索引,导致后续提取的日期字段完全错位。
  2. 日期字段提取错误:DD2 = int(nl[10] + nl[10])重复取同一个索引的字符,会生成错误的日期数值(比如把"26"变成"22"或"66"),当数值超过对应月份的最大天数时,就会触发ValueError。

修复后的代码

from datetime import date

# 用with语句安全读取文件,自动处理关闭操作
with open('a0.txt', 'r') as f:
    lines = f.readlines()

def calculate_date_diff(j):
    # 去除行尾换行符,按制表符分割字段
    parts = lines[j].strip().split('\t')
    # 解包并转换为整数类型
    dd1, mm1, yy1, dd2, mm2, yy2 = map(int, parts)
    # 创建日期对象
    first_date = date(yy1, mm1, dd1)
    second_date = date(yy2, mm2, dd2)
    # 返回日期差的绝对值
    return abs(second_date - first_date)

# 遍历所有行计算并打印日期差
for idx in range(len(lines)):
    print(calculate_date_diff(idx))

修复说明

  • 改用strip()去除每行首尾空白字符,split('\t')按制表符分割字段,彻底避免索引错位问题。
  • 直接解包分割后的字段,代码简洁易读,无需手动拼接字符。
  • 使用with语句管理文件,避免资源泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:57:47