2つの日付の間の日数を計算するためにPythonコードを書きました。コードは正常に動作しますが、シナリオのいずれかで失敗しました。たとえば、開始日が01/01/2016で、終了日が28/02/2016(dd/mm/yyyy形式)の場合、期待外れ58日を置く必要があります。しかし、私のコードは56日の結果を与えます。 以下のコードスニペットです:Pythonを使用して2つの日付間の日数を計算します
##Variable Declaration####################
daysofMonths = [31,28,31,30,31,30,31,31,30,31,30,31]
FinalCount = 0
####### Step 1: Leap Year Function####################################
######################################################################
##if (year is not divisible by 4) then (it is a common year)
##else if (year is not divisible by 100) then (it is a leap year)
##else if (year is not divisible by 400) then (it is a common year)
##else (it is a leap year)
######################################################################
def LeapYear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
####### Step 2: Get the number of days for months Function####################################
def DaysforMonths(month,year):
x = 0
c = 0
for c in range(0,month,1):
if c == 1:
if LeapYear(year)== True:
x = x+29
else:
x = x+28
else:
x = x+ daysofMonths[c]
return x
####### Step 3: Get the inputs from user ###################################
year1 = int(input("Enter the year:"))
month1 = int(input("Enter the month:"))
day1 = int(input("Enter the day:"))
year2 = int(input("Enter the year:"))
month2 = int(input("Enter the month:"))
day2 = int(input("Enter the day:"))
####### Step 3.1: Get number of days between years function ###################################
def TotalDaysBetweenYear(year1,year2):
i = year1
countdays=0
if year1 == year2:
return countdays
else:
for i in range (year1,year2,1):
if (LeapYear(i)== True):
countdays = countdays+366
else:
countdays = countdays+365
return countdays
####### Step 4: Get the number of days between two dates Function####################################
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
FinalCount = TotalDaysBetweenYear(year1,year2) - DaysforMonths(month1,year1)
FinalCount = FinalCount - day1
FinalCount = FinalCount + DaysforMonths(month2,year2)
FinalCount = FinalCount + day2
return FinalCount
print ("Number of days between two date is:",daysBetweenDates(year1, month1, day1, year2, month2, day2))
新しい言語(または学習プログラミング)を学ぶときによく使用されるこの種のタスクは、datetime関数を使用しないことでした。 – Arnial
まあ、私はPythonを学んでいると私はdatetime関数を使用せずにプログラムを書くことを試みていた。 –
@ user2219705おそらく、標準ライブラリとその関数を手に入れて、Pythonを習得する方がいいでしょう。 – Dartmouth