2015-07-02 73 views
1

我的models.py:如何在django模型中通過django表單執行datetime.time類型輸入並對其執行算術運算?

class Attendancename(models.Model): 
    teacher_name = models.ForeignKey(Teachername) 
    date = models.DateField('Date') 
    intime = models.TimeField('IN-TIME') 
    outtime = models.TimeField('OUT-TIME') 

    def hours_conversion(self): 
     tdelta = (datetime.datetime.combine(datetime.date.today(),outtime) - datetime.datetime.combine(datetime.date.today(),intime)) 

     return (tdelta).second/3600 

    def __str__(self): 
     return "%s" %self.teacher_name 

我views.py:

def add_atten(request): 
    if request.method == 'POST': 
     form = AttendancenameForm(request.POST) 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect(reverse('student:listatten')) 
     else: 
      print(form.errors) 
    else:  
     form = AttendancenameForm() 
    return render(request, 'add_atten.html', {'form': form},) 

我forms.py:

class AttendancenameForm(ModelForm): 
     teacher_name = forms.ModelChoiceField(queryset=Teachername.objects.all()) 
    class Meta: 
     model = Attendancename 
     fields = ('teacher_name', 'date', 'intime', 'outtime',) 

我想從'intime''outtime'屬性計算時間差。但我得到意想不到的錯誤:'TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time''。請幫助我使它工作?

回答

0

我不是在Django的專家,但似乎是intimeouttimedatetime.time類型的,你不能使用-運營商相減,而是嘗試使用以下 -

import datetime 
outtime = datetime.time(10,0) 
intime = datetime.time(5,0) 
tdelta = (datetime.datetime.combine(datetime.date.today(),outtime) - datetime.datetime.combine(datetime.date.today(),intime)) 
print(tdelta.seconds/3600) 
+0

謝謝!有用。我怎樣才能把它解釋爲「am''和''pm''的時間差? –

+0

你能解釋一下你的意思嗎?把時間差異解釋爲'am''pm'? datetime.time()不存儲那個信息,它的24小時時鐘 –

+0

如果你正在談論從字符串中解釋它,那麼你可以使用'AM'或'PM'的格式'%p',你也需要通過在當時使用'%I'來格式化小時。 –

相關問題