无法在django中减去两个时间域

rqdpfwrv  于 2023-01-06  发布在  Go
关注(0)|答案(2)|浏览(120)

大家好,我有如下模型。我正试图减去时间和时间。

class Attendance(models.Model):
   employee = models.ForeignKey(Employee, on_delete=models.CASCADE,
                                default=1, related_name='Attendance')
    attendance_date = models.DateField(null=True)
    in_time = models.TimeField(null=True)
    out_time = models.TimeField(null=True, blank=True)
    totaltime = models.TimeField(null=True, blank=True)

    def __str__(self):
        return str(self.employee) + '-' + str(self.attendance_date)

    @property
    def totaltime(self):
        FMT = '%H:%M:%S'
        currentDate = date.today().strftime('%Y-%m-%d')
        sub = datetime.strptime('out_time', FMT) -
            datetime.strptime('in_time', FMT)
        return sub

仍在获取错误:值错误:时间数据"out_time"与格式" %H:%M:%S"不匹配
请告诉我该怎么做,我在想我将如何减去两个时间域

wyyhbhjk

wyyhbhjk1#

@property
def totaltime(self):
    total_time = datetime.timedelta(hours=self.out_time.hour, minutes=self.out_time.minute,
                                    seconds=self.out_time.second) - datetime.timedelta(hours=self.in_time.hour,
                                                                                      minutes=self.in_time.minute,
                                                                                      seconds=self.in_time.second)
    return total_time
wvt8vs2t

wvt8vs2t2#

所以,首先,我们使用total_time作为@属性,这样就可以直接删除字段;其次,我们需要使用timedelta来计算时间之间的差,这是另一个问题出现的地方,因为它似乎只对datetime对象进行操作,所以必须使用work around
models.py:

from datetime import datetime, date, timedelta

class Attendance(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE,
                                default=1, related_name='Attendance')
    attendance_date = models.DateField(null=True)
    in_time = models.TimeField(null=True)
    out_time = models.TimeField(null=True, blank=True)

    def __str__(self):
        return str(self.employee) + '-' + str(self.attendance_date)

    @property
    def total_time(self):
        total = ( datetime.combine(date.today(), self.out_time) - 
                  timedelta(
                        hours=self.in_time.hour, 
                        minutes=self.in_time.minute, 
                        seconds=self.in_time.second
                    ) 
                )
        return total.time()

相关问题