我试图制作一个简单的程序,找出输入的两个日期之间的日差
代码如下:
#program to find the day difference between one date and another
import calendar
date1Y = int(input("input year of date 1")) #putting the input from user to an list in order
date1M = int(input("input month of date 1")) #I don't know how to do this efficiently
date1D = int(input("input day of date 1"))
date2Y = int(input("input year of date 2"))
date2M = int(input("input month of date 2"))
date2D = int(input("input day of date 2"))
list_date1 = [date1Y, date1M, date1D] #lists of the first and second date in order Y/M/D
list_date2 = [date2Y, date2M, date2D]
days = 0
if list_date1(0) < list_date2(0) or (list_date1(0) == list_date2(0) and list_date1(1) < list_date2(1)):
while (list_date1(0) != list_date2(0) and list_date1(1) != list_date2(1)):
while (list_date1(1) <= 12):
a = calendar.monthrange(list_date1(0), list_date1(1))
days_month = a[1]
days += a[1]
list_date1(1) += 1
else :
list_date1(0) += 1
list_date1(1) = 0
elif list_date2(0) < list_date1(0) or (list_date1(0) == list_date2(0) and list_date2(1) < list_date1(1)):
while (list_date1(0) != list_date2(0) and list_date1(1) != list_date2(1)):
while (list_date2(1) <= 12):
a = calendar.monthrange(list_date2(0), list_date2(1))
days_month = a[1]
days += a[1]
list_date2(1) += 1
else :
list_date2(0) += 1
list_date2(1) = 0
if (date1D > date2D): #adding the day differences of the 2 dates
days = days + (date1D-date2D)
else :
days = days + (date2D-date1D)
print("the number of days difference =", str(days))
由于
list_date1
和list_date2
都是列表,因此从中访问元素将使用方括号而不是常规括号。尝试将所有list_date#(#)
更改为list_date#[#]
例如,使用列表
x = [1, 2, 3]
打印x[1]
将打印2
,因为列表索引从0开始相关问题 更多 >
编程相关推荐