How to calculate the difference between two dates in OpenERP?

安稳与你 提交于 2019-12-23 05:26:19

问题


In my custom module I am unable to calculate difference between two dates.

My field is

'date_s':fields.datetime('Start Date'),
'date_e':fields.datetime('End Date'),

I want to calculate the difference automatically in my duration field:

 'Duration':fields.char('Duration'),

回答1:


this is a simple function I have written. Hope it will help you.

def onchange_return_date(self, cr, uid, ids, issuedate, returndate):
 a=datetime.strptime(issuedate,"%Y-%m-%d")
 b=datetime.strptime(returndate,"%Y-%m-%d")
 timedelta = b - a
 diff=timedelta.days
 return {'value': {'days':diff}}



回答2:


  1. use a function field for that purpose: https://doc.openerp.com/trunk/server/03_module_dev_02/#functional-fields , there are some nice examples within the addons to get a clue about this type of fields.

  2. think about using date or datetime again. if you don't need time then just use date...

for further questions, just ask :-)

edit: try your function that way

import openerp.tools as tools
import datetime
def _get_days(self, cr, uid, ids, field_name, args, context=None):
    res = {}
    for date in self.browse(cr, uid, ids, context=context):
        fmt = tools.DEFAULT_SERVER_DATETIME_FORMAT
        date_s = datetime.datetime.strptime(date.date_s, fmt)
        date_e = datetime.datetime.strptime(date.date_e, fmt)
        res[date.id] = (date_e-date_s).days or False
    return res


来源:https://stackoverflow.com/questions/22473484/how-to-calculate-the-difference-between-two-dates-in-openerp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!