2017-02-27 45 views
0

我想创建一个模块,可以这样做:inputdate =“2017年2月27日”,nomonths = 2,因此outputdate必须为“2017年4月27日”。 inputdate和nomonths是我们必须填写的两个字段,并且odoudate只是odoo中的一个“只读”字段。在Odoo 10中添加几个月到日期时间

class DateGenerate(models.Model): 
    _name = "studentmanagement.dategenerate" 

    inputdate = fields.Date() 
    nomonths = fields.Integer(required=True) 
    outputdate = fields.Date(readonly=True) 

    @api.onchange('inputdate','nomonths') 
    def add_month(self): 
     for record in self: 
      dt = fields.Datetime.to_string(record.inputdate) 
      inpYear = datetime.strptime(dt,"%Y") 
      inpMonth = datetime.strptime(dt,"%m") 
      inpDay = datetime.strptime(dt,"%d") 
      outYear = inpYear + int((inpMonth + record.nomonths - 1)/12) 
      outMonth = (inpMonth + record.nomonths - 1) % 12 + 1 
      record.outputdate = datetime.date(outMonth, inpDay, outYear) 

XML

我写一个基于互联网上的资源和解释的代码,但它不工作,导致错误: enter image description here

我从这些读码和方向链接

https://docs.python.org/2/library/datetime.html https://github.com/odoo/odoo/blob/10.0/odoo/fields.py#L1504

回答

0

要添加/将日期添加到日期/日期时间对象我建议使用python包:dateutil.relativedeltahttp://dateutil.readthedocs.io/en/stable/relativedelta.html

基本用法:

from datetime import date, datetime 
from dateutil.relativedelta import relativedelta 

print date.today() + relativedelta(months=+3) 
print datetime.today() + relativedelta(months=+3) 

print date.today() - relativedelta(months=+3) 
print datetime.today() - relativedelta(months=+3) 

你的问题同时引用datetimedate对象,因此已包括了两个例子。

希望这会有所帮助。

+0

我们可以做到这一点: “record.outputdate = record.inputdate + relativedelta(months = + record.nomonths)”。记录是odoo数据库自身的一行,但它会导致错误:“File”dateutil \ relativedelta.pyc“,第247行,在__radd__中 TypeError:不支持的类型用于添加操作” –

+0

是您的record.inputdate python日期或日期时间对象?并且是你的记录.nomonths是一个整数? –

+0

nomonths是一个整数,但record.inputdate是ODOO中的一个日期对象,而不是python。所以我想这是错误,但我不知道如何在odoo中添加/获取日期。 –