[英]How to find day difference between two dates?
我试图制作一个简单的程序来查找输入的 2 个日期之间的日期差异。
这是代码:
#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 开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.