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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31156031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:34:11  来源:igfitidea点击:

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

pythondjango-modelsdjango-templatesdjango-views

提问by Gaurav Tomer

my models.py:

我的模型.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:

我的意见.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:

我的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',)

Actually I'm trying to calculate total number of hours based on difference of 'intime'and 'outtime'in my models.py file but it raises above erroe. I think I'm doing syntax error. Can anybody Please tell me what is the correct syntax or method to do so? Any body please suggest me what to do to fix it?

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

回答by OldTinfoil

It's because you cannot subtract a datetime.timefrom a datetime.time. Convert them to datetime.datetimeobjects and it'll return a datetime.timedeltaobject that you could use.

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

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

如果您有幸使用Django 1.8,他们现在有一个DurationField可以使用的。

Failing that, I would recommend converting the timedeltainto either seconds or a floating point representation so you can actually store it to the database.

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

EDIT:Pulled up in comments for half arsing an answer.

编辑:在评论中拉起半个回答。

For example - if you want to store the number of (integer) seconds, you can convert from a TimeDeltaby using secs = td // timedelta(seconds=1).

例如 - 如果要存储(整数)秒数,可以TimeDelta使用secs = td // timedelta(seconds=1).