TypeError:不支持的操作数类型 - :' datetime.time'和' datetime.time'

时间:2015-07-01 08:16:59

标签: python django-models django-templates django-views

my models.py:

class Attendancename(models.Model):
    teacher_name = models.ForeignKey(Teachername, default='Ram')
    date = models.DateField('Date', default=datetime.datetime.today)
    intime = models.TimeField('IN-TIME', auto_now=True)
    outtime = models.TimeField('OUT-TIME', auto_now=True)

    def hours_conversion(self):
        startdelta = datetime.timedelta(hours=self.intime.hours, minutes=self.intime.minutes, seconds=self.intime.seconds)
        enddelta = datetime.timedelta(hours=self.outtime.hours, minutes=self.outtime.minutes, seconds=self.outtime.seconds)
        return (enddelta-startdelta).seconds/3600

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

my 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},)

my forms.py:

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

实际上,我尝试根据models.py文件中'intime''outtime'的差异来计算总小时数,但它会提高到错误率。我想我在做语法错误。任何人都可以告诉我这样做的正确语法或方法是什么? 任何人都请建议我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:6)

这是因为您无法从datetime.time中减去datetime.time。将它们转换为datetime.datetime个对象,它将返回一个您可以使用的datetime.timedelta对象。

If you're lucky enough to be using Django 1.8, they now have a DurationField that can be used.

如果不这样做,我建议将timedelta转换为秒或浮点表示,以便您可以将其实际存储到数据库中。

编辑:在评论中拉了半个答案。

例如 - 如果要存储(整数)秒的数量,可以使用TimeDeltasecs = td // timedelta(seconds=1)转换。