2015-10-13 61 views
0

我需要比较两个时间字段值并计算总工作时间。Django时间字段差异

我的功能(我想什么)

def difft(start,end): 
    a,b,c,d = start.hour, start.minute, start.second, start.microsecond 
    w,x,y,z = end.hour, end.minute, end.second, end.microsecond 
    delt = (w-a)*60 + (x-b) + (y-c)/60. + (z-d)/60000000 
    return delt + 1440 if delt<0 else delt 

def myfunction(): 
    attendance = StaffAttendance.objects.get(id=1) 

    time_sheets = []  

    t_times = TimeSheet.objects.filter(staff_attendance=attendance,is_deleted=False).order_by("time") 
    for t in t_times: 
     time_sheets.append(t.time) 

    #timesheets = [datetime.time(4, 0), datetime.time(6, 0)] 

    total_time = 0 
    times = [] 

    for time in time_sheets: 
     if time in times: 
      m = difft(times[0],time) 
      total_time += m 
      times = [] 
     else: 
      times.append(time) 

if time in times:这一块总是返回False

如何计算django时间字段的总工作时间。我是Python/Django的新手。所以我对python日期不太了解。你能帮我解决这个问题吗?谢谢。

+0

你可以放一个打印语句来看看'time_sheets'和'times'的值在循环中吗? – karthikr

+0

'if time in times:'总是会返回false,因为'times'是一个空列表('[]')。 – Leistungsabfall

+0

[计算时间差]的可能重复(http://stackoverflow.com/questions/3426870/calculating-time-difference) – eykanal

回答

0

如果time_sheets具有唯一的时间数据,您的if语句将始终返回false。我很困惑你想在循环中做什么。也许你想检查时间不在时间,因为你得到的时间没有处理,你可以使用difft函数,你可以追加处理时间到时间表。