gpt4 book ai didi

python - 日期时间字段和时间字段错误

转载 作者:行者123 更新时间:2023-12-01 09:31:23 26 4
gpt4 key购买 nike

我的代码工作得很好,但由于我的需求发生了变化,我必须将 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)

最佳答案

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

关于python - 日期时间字段和时间字段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49947856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com