首页 > 解决方案 > Django,如何将持续时间字段设置为两个日期时间字段之间的差异

问题描述

我有一个 Django 模型,我想根据两个 DateTime 字段的输入数据计算持续时间字段,并将它们之间的差异存储为小时:分钟(我什至不确定持续时间字段是否是正确的选择。

这是我到目前为止得到的。

class CarEventsData(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="events_of_cow")
    out = models.DateTimeField(null=True, help_text="When the cow went OUT TO Pasture.")
    _in = models.DateTimeField(null=True, help_text="When the cow got back IN FROM Pasture.")
    duration = models.DurationField()

    def save(self, *args, **kwargs):
        """
        Should set duration field to total time between out and in data.
        """
        self.duration = self.out - self._in
        super(CarEventsData, self).save(*args, **kwargs)

标签: pythondjangodjango-modelsdurationpython-datetime

解决方案


您可以添加辅助功能

helper.py
def get_overtime_application_hours(start_time, end_time) -> int:
    difference = end_time - start_time
    hours = difference.seconds/3600
    return hours 

导入您的模型

from .healper import get_overtime_application_hours

然后

def duration(self):
    hours = get_overtime_application_hours(self.out, 
                self._in)
    return round(hours) 

推荐阅读