问题
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:
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.
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