This coding is to find the days between dates.my coding is not working for the case which i mentioned as comment at last of code, pls specify my error (note : (y1,m1,d1) -> start date and (y2,m2,d2) -> end date)
def days_between_dates(y2,m2,d2,y1,m1,d1):
days = 0
tot = 0
while not(y1==y2 and m1==m2 and d1==d2):
days = days + 1
d1 = d1+1
if((m1 == 4 or m1 == 6 or m1 == 9 or m1 == 11) and d1 == 30):
d1 = 0
m1 = m1+1
if(d1 == 31):
d1 = 0
m1 = m1+1
if (((y1%4)!=0) and m1 == 2 and d1==28):
d1 = 0
m1 = m1+1
else:
if(m1 == 2 and d1 == 29):
d1 = 0
m1 = m1+1
if(m1>12):
m1 = 1
y1 = y1 + 1
if(y1==y2 and m1==m2 and d1==d2):
return days
break
return days
print days_between_dates(2011,1,1,2010,1,1)
print days_between_dates(2013,1,1,2012,1,1)
#print days_between_dates(2012,2,29,2012,2,28)
Avoid reinventing the wheel, and use the datetime
module instead:
from datetime import date
def days_between_dates(y2, m2, d2, y1, m1, d1):
return (date(y2, m2, d2) - date(y1, m1, d1)).days
As for your error: You are using 0-based date arithmetic; whenever you come to the end of a month, you switch to day 0 of the next month. This means you will never hit the end condition if the y2, m2, d1
day is the last day of the month, for example; before you test for 2012, 2, 29
you already changed the date to 2012, 3, 0
.
Use 1-based arithmetic, and only change the month when you get beyond the last day of that month.
Note that you can test equality between tuples, no need to do a full test against each element. Your leap year calculation needs a little refinement too:
def is_leap_year(year):
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 0
def days_between_dates(y2, m2, d2, y1, m1, d1):
days = 0
isleapyear = is_leap_year(y1)
while (y1, m1, d1) != (y2, m2, d2):
days += 1
d1 += 1
if (m1 == 2 and d1 == (30 if isleapyear else 29) or
m1 in (4, 6, 9, 11) and d1 == 31 or d1 == 32):
d1 = 1
m1 += 1
if m1 == 13:
m1 = 1
y1 += 1
isleapyear = is_leap_year(y1)
return days
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다