我有三个字段start_date
,end_date
和total_days
。
如果我输入start_date
和end_date
字段,则应自动显示total_days
。
这是我的功能无效。
<field name="start_date" on_change="get_number_of_days(start_date,end_date)"/>
<field name="end_date" on_change="get_number_of_days(end_date,start_date)"/>
<field name="total_days" />
def get_number_of_days(self, cr, uid, ids, start_date, end_date):
"""Returns a float equals to the timedelta between two dates given as string."""
result = self.browse(cr, uid, ids)
if (end_date and start_date) and (start_date <= end_date):
DATETIME_FORMAT = "%d/%m/%Y %H:%M:%S"
from_dt = datetime.datetime.strptime(start_date, DATETIME_FORMAT)
to_dt = datetime.datetime.strptime(end_date, DATETIME_FORMAT)
timedelta = to_dt - from_dt
diff_day = timedelta.days + float(timedelta.seconds) / 86400
result['value']['total_days'] = round(math.floor(diff_day))+1
return result
还有其他方法吗?或者可能是什么问题
答案 0 :(得分:2)
部分:
diff_day = timedelta.days + float(timedelta.seconds) / 86400
result['value']['total_days'] = round(math.floor(diff_day))+1
在很大程度上是不必要的,因为datetime.timedelta
已经将整天的数量作为值timedelta.days
- 我怀疑你的问题是你没有转换为字符串试试:
result['value']['total_days'] = str(timedelta.days)
当strptime
函数无法转换当前值时,您还应考虑捕获问题,例如当它是空白时。
答案 1 :(得分:2)
如果您的日期以字符串形式给出(正如您的文档字符串所示),则条件的第二部分可能会出现意外行为(取决于日期/时间格式),因为您执行了字典比较:
Next
您应该将它们转换为datetime-objects first ,然后检查您的条件。
答案 2 :(得分:0)
谢谢,
我为此编写了新功能,这有助于提供总天数:
def _get_days(self, cr, uid, ids, field_name, arg ,context=None):
res = {}
fmt = '%Y-%m-%d'
for object in self.browse(cr, uid, ids, context=context):
res[object.id] = {'total_days':0, }
from_date = object.start_date
to_date = object.end_date
d1 = datetime.strptime(from_date, fmt)
d2 = datetime.strptime(to_date, fmt)
daysDiff = str((d2-d1).days+1)
res[object.id]['total_days'] = daysDiff
return res
'start_date': fields.date('Start Date', required=True),
'end_date': fields.date('End Date', required=True),
'total_days': fields.function(_get_days, string="Diff days", multi='sums', store=True),