python - 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)
解决方案
您可以添加辅助功能
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)
推荐阅读
- azure - Azure Kubernetes 服务:如何为整个节点池设置污点?
- node.js - 如何使用 Mongoose 将元素推送到对象数组中?
- elasticsearch - 负载在 cpu 核心之间分布不均 - Elasticsearch
- api - 如何轻松记录 REST API
- python - 使用 Python 的子进程将 Wav 转换为 Wav
- plotly - 向用户发出丢失数据的信号
- javascript - 需要将 curl 命令解析为 Javascript 对象
- sql - SQL 方法填充唯一标识符的空白行
- python - Pyinstaller PyQt5 ModuleNotFoundError 第二个窗口不会打开
- javascript - 我尝试在结帐页面显示表格的方式有问题吗?