zoukankan      html  css  js  c++  java
  • 计算两个日期之间相差多少个小时

    题目描述:

    给定两个日期,例如2009120311和2008110413,格式为年/月/日/小时,求两个日期之间相差多少个小时。

    思考:

    第一感似乎应该先计算相差多少年,然后多少个月,多少天,多少个小时,然后累加就好了,但是似乎没有这么简单:

    1.闰年和平年

    2.每个月的天数不一样

    3.闰年二月和平年二月

    4.相减不够怎么办

    上面的这些问题都是应该想到的,如果想到这些问题,那么应该就可以写代码了。

    首先写个判断闰年还是平年的函数:

    def dayOfYear(year):
    	if (year%4==0&year%100!=0)|(year%400==0):
    		return 1
    	else:
    		return 0
    

     然后我的思路是,计算每个日期,在当前年是处在第多少个小时,然后计算两个年之间相差多少小时,两者合并,就可以计算出两个日期相差多少个小时,代码如下:

    def diffHours(date1, date2):
    	dayOfMonth = (31,28,31,30,31,30,31,31,30,31,30,31)
    	temp1 = date1
    	temp2 = date2
    
    	hour1 = temp1%100
    	temp1 = temp1/100
    	hour2 = temp2%100
    	temp2 = temp2/100
    
    	day1 = temp1%100
    	temp1 = temp1/100
    	day2 = temp2%100
    	temp2 = temp2/100
    
    	month1 = temp1%100
    	temp1 = temp1/100
    	month2 = temp2%100
    	temp2 = temp2/100
    
    	year1 = temp1
    	year2 = temp2
    
    	print year1, month1, day1, hour1
    	print year2, month2, day2, hour2
    
    	total1 = hour1
    	total1 += 24 * (day1 - 1)
    	for i in range(month1-1):
    		total1 = total1 + dayOfMonth[i]
    		if i==1:
    			total1 = total1 + dayOfYear(year1)
    
    
    	total2 = hour2
    	total2 += 24 * (day2 - 1)
    	for i in range(month2 - 1):
    		total2 = total2 + dayOfMonth[i]
    		if i==1:
    			total2 = total2 + dayOfYear(year2)
    
    
    	flag = 1
    	totalDay = 0
    	if year1 < year2:
    		temp = year1
    		year1 = year2
    		year2 = temp
    		flag = -1
    	while(year1<year2):
    		totalDay += 365 + dayOfYear(year1)
    		year1 +=1
    
    	if flag == 1:
    		total1 = total1 + totalDay * 24
    	else:
    		total2 = total2 + totalDay * 24
    
    	print total1,total2
    	return total1 - total2
    
  • 相关阅读:
    面试经验
    二叉树和递归
    优先队列
    队列问题
    书法学习资料
    栈的问题
    Git常用命令
    字母大小写转换
    深入类中的方法[8] - 抽象方法与抽象类
    深入类中的方法[7] - 关于 inherited
  • 原文地址:https://www.cnblogs.com/xiamaogeng/p/4460980.html
Copyright © 2011-2022 走看看