在odoo 10.0中添加日期

时间:2017-02-26 15:16:41

标签: python openerp odoo-10

我有一个班级:

class DateAddition(models.Model):
      _name = "studentmanagement.dateaddition"

      input_date = fields.Date()
      output_date = fields.Date()
      no_months = fields.Integer()

然后,如果我填写input_date =“2017年2月26日”和no_months = 2,则output_date将为“2017年4月26日”。我如何通过on_change在odoo-10.0中完成?

1 个答案:

答案 0 :(得分:1)

我不知道如何将其与您的odoo on_change挂钩,但这是一个从日期字符串中添加或减去月份的例程:

<强>代码:

import datetime as dt

def add_month(date, months):
    assert isinstance(date, dt.date)
    year, month, day = date.year, date.month, date.day
    year += int((month + months-1) / 12)
    month = (month + months - 1) % 12 + 1
    return dt.date(year, month, day)

def add_month_from_string(date_string, months):
    date = dt.datetime.strptime(date_string, '%d %b %Y')
    return add_month(date, months).strftime('%d %b %Y')

测试数据:

test_data = (
    ("26 Feb 2017", 2, "26 Apr 2017"),
    ("6 Dec 2016", 3, "6 Mar 2017"),
    ("26 Feb 2017", -2, "26 Dec 2016"),
)

for have, inc, want in test_data:
    print(have, inc, add_month_from_string(have, inc), want)

<强>结果:

('26 Feb 2017', 2, '26 Apr 2017', '26 Apr 2017')
('6 Dec 2016', 3, '06 Mar 2017', '6 Mar 2017')
('26 Feb 2017', -2, '26 Dec 2016', '26 Dec 2016')