DateTimeField& TimeField错误

时间:2018-04-20 18:39:21

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

我的代码工作正常,但是由于我的需求变化,我不得不将DateTimeField设置为TimeField,但在我的代码中进行更改之后,我遇到了以下错误。

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

我的代码是关于工资计算的。

class salary(models.Model):
#employee = models.ForeignKey('employee', on_delete=models.CASCADE)
base_salary = models.IntegerField(default=0)
time_in = models.DateTimeField(default=tz.now, null=True, blank=True)
time_out = models.DateTimeField(default=tz.now, null=True, blank=True)
total_salary = models.CharField(max_length=20, default='0')

def calculate_salary(self):
    worked_hours = (self.time_out - self.time_in).total_seconds() / 60 / 60
    overtime_hours = 0

    # make sure you use timezone aware objects
    # https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/#naive-and-aware-datetime-objects
    same_day_8pm = self.time_out.replace(hour=16, minute=0, second=0, microsecond=0)
    if self.time_out > same_day_8pm:
        overtime_hours = (self.time_out - same_day_8pm).total_seconds() / 60 / 60

    salary_1 = worked_hours * self.base_salary
    salary_2 = overtime_hours * self.base_salary * 0.2
    total_salary = salary_1 + salary_2

    # careful: this will be a 'float', not an 'int'
    # with round() using 0 decimal digits you get an 'int'
    # total_salary = round(total_salary, 0)

    return total_salary

def save(self,*args,**kwargs):
    # are you really sure that you want to save a string ???
    self.total_salary = str(self.calculate_salary())
    super().save(*args, **kwargs)

1 个答案:

答案 0 :(得分:1)

可以减去Python datetime.datetime个对象,但datetime.time个对象不能。您可以使用当前日期将它们组合到datetime个对象中来减去它们(请参阅,例如https://stackoverflow.com/a/5259921/2715819)。具体来说,尝试更改

worked_hours = (self.time_out - self.time_in).total_seconds() / 60 / 60

为:

datetime_in = datetime.combine(date.min, self.time_in)
datetime_out = datetime.combine(date.min, self.time_out)
worked_hours = (datetime_out - datetime_in).total_seconds() / 60 / 60

您还必须在文件顶部添加from datetime import datetime, date。您还必须将overtime_hours的计算更改为使用datetime_out而不是self.time_out

相关问题