Title Description:
Given two dates, such as 2009120311 and 2008110413, the format is year/month/day/hour, and the number of hours between two dates is different.
Thinking:
The first feeling seems to be to calculate the difference of how many years, then how many months, how many days, how many hours, and then accumulate on the good, but does not seem so simple:
1. Leap years and common year
2. The number of days per month is different
3. Leap year February years of peace
4. What to do if the subtraction is not
The above questions should be thought of, if you think of these problems, then you should be able to write code.
First, write a function that judges the leap year or common year:
Def dayofyear (year): if (year%4==0&year%100!=0) | (year%400==0): return 1else:return 0
Then my idea is, calculate each date, in the current year is in the number of hours, and then calculate the difference between two years of how many hours, the combination of the two, you can calculate the difference of two dates how many hours, the code is as follows:
def diffhours (date1, date2):d Ayofmonth = ( 31,28,31,30,31,30,31,31,30,31,30,31) Temp1 = DATE1TEMP2 = Date2hour1 = TEMP1%100TEMP1 = TEMP1/100HOUR2 = TEMP2%100TEMP2 = t Emp2/100day1 = TEMP1%100TEMP1 = Temp1/100day2 = TEMP2%100TEMP2 = Temp2/100month1 = TEMP1%100TEMP1 = Temp1/100month2 = Temp 2%100TEMP2 = Temp2/100year1 = Temp1year2 = Temp2print year1, month1, Day1, Hour1print year2, Month2, day2, Hour2total1 = h Our1total1 + = (day1-1) for I in Range (month1-1): Total1 = total1 + dayofmonth[i]if i==1:total1 = Total1 + dayofyear (y EAR1) Total2 = hour2total2 + * (day2-1) for I in Range (month2-1): Total2 = Total2 + dayofmonth[i]if I==1:total2 = tot Al2 + dayofyear (year2) flag = 1totalDay = 0if year1 < year2:temp = Year1year1 = Year2year2 = Tempflag = -1while (year1< ; year2): Totalday + = 365 + dayofyear (year1) year1 +=1if flag = = 1:total1 = Total1 + totalday * 24else:total2 = Total2 + Tota Lday * 24print Total1,total2return total1-total2
Calculate how many hours are different between two dates