计算两小时之间的差异
我想计算两个时间之间的差异使用django
在sql db
的时间存储在时间字段。
我试过这个:
def DesigInfo(request): # attendance summary
emplist = models.staff.objects.values('empId', 'name')
fDate = request.POST.get('fromDate')
tDate = request.POST.get('toDate')
if request.GET.get('empId_id'):
sel = attendance.objects.filter(empId_id=request.GET.get('empId_id'),)
for i in sel:
# print i.
# print i.outTime
# print i.inTime.hour,i.inTime.minute,i.inTime.second - i.outTime.hour,i.outTime.minute,i.outTime.second
ss = i.inTime.hour
ss1 = 12 - ss
mm = i.outTime.hour
mm1 = (12 + mm) - 12
print ss1 + mm1
由于i.inTime
和i.outTime
是时间对象,因此不能简单地将它们相减。 一种好的方法是将它们转换为datetime添加日期部分(今天使用(),但与差异无关),然后减去获得timedelta对象。
delta = datetime.combine(date.today(), i.outTime) - datetime.combine(date.today(), i.inTime)
(看这里:在Python中减去两次)
那么如果你想以小时表示delta
:
delta_hours = delta.days * 24 + delta.seconds / 3600.0
timedelta对象具有3个属性,代表时间差异(日,秒和微秒)的3种不同分辨率。 在最后一个表达式中,我避免添加微秒,但我认为它与您的情况无关。 如果它也是增加delta.microseconds / 3600000000.0
注意简单地将秒除以3600将只返回小数的整数部分,以避免分数。 这取决于您的业务规则如何将其整理起来(圆形,平面,小面或像我一样离开小数部分)
使用datetime对象:https://docs.python.org/2/library/datetime.html
关于如何在Python中获取当前时间这一主题的一个很好的堆栈溢出帖子
from datetime import datetime
now = datetime.now()
# wait some time
then = ... some time
# diff is a datetime.timedelta instance
diff = then - now
diff_hours = diff.seconds / 3600
你可能想玩这个代码:
from datetime import datetime
#set the date and time format
date_format = "%m-%d-%Y %H:%M:%S"
#convert string to actual date and time
time1 = datetime.strptime('8-01-2008 00:00:00', date_format)
time2 = datetime.strptime('8-02-2008 01:30:00', date_format)
#find the difference between two dates
diff = time2 - time1
''' days and overall hours between two dates '''
print ('Days & Overall hours from the above two dates')
#print days
days = diff.days
print (str(days) + ' day(s)')
#print overall hours
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = days_to_hours + diff_btw_two_times
print (str(overall_hours) + ' hours');
''' now print only the time difference '''
''' between two times (date is ignored) '''
print ('nTime difference between two times (date is not considered)')
#like days there is no hours in python
#but it has seconds, finding hours from seconds is easy
#just divide it by 3600
hours = (diff.seconds) / 3600
print (str(hours) + ' Hours')
#same for minutes just divide the seconds by 60
minutes = (diff.seconds) / 60
print (str(minutes) + ' Minutes')
#to print seconds, you know already ;)
print (str(diff.seconds) + ' secs')
链接地址: http://www.djcxy.com/p/40923.html