如何计算数据库中存储的两个日期之间的天数?

时间:2018-06-28 19:31:33

标签: python odoo-9

我正在尝试制作一个模块,该模块从数据库中获取两个不同的日期,即 create_date won_date ,计算它们之间的天数并存储结果在新字段 compare_dates 中。

这是代码:

def action_set_won(self, cr, uid, ids, context=None):
    """ Won semantic: probability = 100 (active untouched) """
    stages_leads = {}
    for lead in self.browse(cr, uid, ids, context=context):
        stage_id = self.stage_find(cr, uid, [lead], lead.team_id.id or False, [(
            'probability', '=', 100.0), ('on_change', '=', True)], context=context)
        if stage_id:
            if stages_leads.get(stage_id):
                stages_leads[stage_id].append(lead.id)
            else:
                stages_leads[stage_id] = [lead.id]
    for stage_id, lead_ids in stages_leads.items():
        self.write(cr, uid, lead_ids, {'stage_id': stage_id}, context=context)
    return self.write(cr, uid, ids, {'probability': 100, 'won_date': datetime.now(), 'compare_dates': abs('won_date' - 'create_date')}, context=context)

和odoo说:

File "/mnt/extra-addons/crm_updates/models/models.py", line 37, in action_set_won
return self.write(cr, uid, ids, {'probability': 100, 'won_date': datetime.now(), 'compare_dates': abs(('won_date') - ('create_date'))}, context=context)

TypeError:--'str'和'str'的不受支持的操作数类型

知道怎么办。

1 个答案:

答案 0 :(得分:2)

这是一个相当简单的解决方案:

# You need the datetime package to calculate between dates
from datetime import datetime 
compare_dates = abs((won_date - create_date).days)

给出更多信息here