我想计算两个日期之间的差,并在duree
字段中以天为单位计算持续时间
我的file.py是:
date_debut= fields.Date(string="Date debut")
date_fin= fields.Date(string="Date fin")
duree= fields.Date(string="Durée")
答案 0 :(得分:0)
from datetime import datetime as dt
date_debut = fields.Date(string="Date debut")
date_fin = fields.Date(string="Date fin")
duree = fields.Char(string="Durée", compute="_duration", store=True)
@api.depends('date_debut','date_fin')
def _duration(self):
if self.date_debut and self.date_fin:
for rec in self:
init_date = dt.strptime(rec.date_debut, '%Y-%m-%d')
end_date = dt.strptime(rec.date_fin, '%Y-%m-%d')
rec.duree= str((end_date - init_date).days)
答案 1 :(得分:0)
请首先导入以下内容:
import datetime
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DF
然后以下代码将为您计算两个日期之间的差额:
date_debut= fields.Date(string="Date debut")
date_fin= fields.Date(string="Date fin")
duree= fields.Char(string="Durée", compute="compute_duration")
def display_hours_minutes(self, seconds, granularity=2):
result = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append("{} {}".format(value, name))
return ', '.join(result[:granularity])
def compute_duration(self)
for r in self:
date_debut = datetime.datetime.strptime(r.date_debut, DF + ' %H:%M:%S')
date_fin = datetime.datetime.strptime(r.date_fin, DF + ' %H:%M:%S')
date_diff = date_fin - date_debut
r.duree = r.display_hours_minutes(date_diff.seconds)
输出将如下所示:
0 Days, 23 hours, 45 minutes