我试图使用日期时间模块计算日期,但是当我在定义中输入
1
时,它向我显示:dates
奇怪的是,当我在定义中输入
41 days, 0:00:00
Traceback (most recent call last):
File "", line 22, in <module>
print(dates(i))
^^^^^^^^
File "", line 18, in dates
SD = date(YY2, MM2, DD2)
^^^^^^^^^^^^^^^^^^^
ValueError: day is out of range for month
时,它给了我一个很好的结果,与
0
不同。日期取自 txt 文件。1
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))
这是因为您当天的计算不正确:
date(2024,3,0)
您使用了
DD2 = int(nl[10] + nl[10])
两次。您打算使用
nl[10]
和 nl[10]
。