給你兩個日期,問這兩個日期相差幾天。

輸入說明
輸入有多筆測資,每筆測資有兩行,每行有三個整數依序是年、月、日。輸入以 EOF 作為結束,題目保證不會有不符合的測資出現。

輸出說明
輸出兩個日期差幾天。

上面的程式碼是此題的標準解法, 需要用到 datatime 函式庫, 不然運行會 TLE(超時)
下面的程式碼為邏輯程式碼, 一樣是正確的版本, 本地可執行, 驗證 TLE
python for 迴圈容易占用過多時間


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from datetime import date

while True:
try:
# 讀取輸入日期
year1, month1, day1 = map(int, input().split())
year2, month2, day2 = map(int, input().split())

# 轉換成 date 物件
date1 = date(year1, month1, day1)
date2 = date(year2, month2, day2)

# 計算日期差
delta = (date2 - date1)

# 輸出結果
if int(delta.days)<0:
print(-delta.days)
else:
print(delta.days)


except:
# 輸入結束
break

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def leap_check(year):
if (year%400==0) or (year%4==0 and year%100!=0):
return 1
else:
return 0

def leap_year_sum_day(year): # 回傳年天數
if leap_check(year):
return 366
else:
return 365

def leap_month_sum_day(month,year): # 回傳該月份累積天數
leap_year_day_add=[0,31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
not_leap_year_day_add=[0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
if leap_check(year):
return leap_year_day_add[month-1]
else:
return not_leap_year_day_add[month-1]

while True:
try:
head=list(map(int,input().split()))
tail=list(map(int,input().split()))
if head[0]>tail[0] or (head[0]==tail[0] and head[1]>tail[1]) or (head[0]==tail[0] and head[1]==tail[1] and head[2]>tail[2]):
temp=list(tail)
tail=list(head)
head=list(temp)
sum_day=0
for i in range(head[0]+1,tail[0],1):
sum_day=sum_day+leap_year_sum_day(i)

if head[0]!=tail[0]:
sum_day=sum_day+leap_month_sum_day(tail[1],tail[0])+tail[2]+leap_year_sum_day(head[0])-leap_month_sum_day(head[1],head[0])-head[2]# 計算 tail 年累積天數 +head 年剩餘天數
else:
sum_day=sum_day+leap_month_sum_day(tail[1],tail[0])+tail[2]-leap_month_sum_day(head[1],head[0])-head[2]
print(leap_month_sum_day(tail[1],tail[0]),tail[2],leap_month_sum_day(head[1],head[0]),head[2])
print(sum_day)
except:
break

a263. 日期差幾天



作者: 微風