- #!/usr/bin/env python
- # Created on 2012-7-5 by Eric
- # About calculate the days between the two dates
- def isComYear(year):# judge if a certain year is a common year in which February only has 28 days
- if year%100 == 0:
- if (year/100)%4 == 0:
- return 0
- else:
- return 1
- else:
- if year%4 == 0:
- return 0
- else:
- return 1
- def daysInMonth(year,month):#calculate the total days in a certain month in a certain year
- bigMonth = [1, 3, 5, 7, 8, 10, 12]
- if month in bigMonth:
- return 31
- elif month == 2:
- if isComYear(year):
- return 28
- else:
- return 29
- else:
- return 30
- def daysInYear(year):#calculate the total days in a certain year
- if isComYear(year):
- return 365
- else:
- return 366
- def distance(date1,date2): # first sort the two date
- list1 = []
- list2 = []
- result = 0
- for ele in date1.split("/"):
- list1.append(int(ele))
- for ele in date2.split("/"):
- list2.append(int(ele))
- print list1
- print list2
- list1,list2 = min(list1,list2),max(list1,list2)
- if list1[0] == list2[0]: # equal year
- if list1[1] == list2[1]: # equal month
- result = list1[2] - list2[2]
- else:
- result1 = 0
- for month in range(list1[1],list2[1]):
- result1 += daysInMonth(list1[0],month)
- result = result1 - list1[2] + list2[2]
- else:
- #if year is not equal,we won't care if the month is equal.We will only
- #care the first year's remaining days,the last year's passed days and the total days between the two years
- result2 = 0
- result3 = 0
- result4 = 0
- for year in range(list1[0],list2[0]):
- result2 += daysInYear(year)
- if list1[1] == 1:
- result3 = list1[2] - 1
- else:
- for month in range(1,list1[1]):
- result3 += daysInMonth(list1[0],month)
- if list2[1] == 1:
- result4 = list[2]
- else:
- for month in range(1,list2[1]):
- result4 += daysInMonth(list2[0],month)
- result = result2 - result3 + result4
- return result
- def main():
- date1 = raw_input("input the first date in the format YY/MM/DD : ")
- date2 = raw_input("input the second date in the format YY/MM/DD: ")
- dist = distance(date1,date2)
- print "the distance between the two date is:",abs(dist)
- if __name__ == '__main__':
- main()
转载于:https://blog.51cto.com/tianhao936/925557