如何将整数添加到日期字段

问题描述

我是 odoo 的初学者。所以我做了一个名为 Hotel management 的模块,我有一个名为“Expected_days”的整数字段,用户可以在其中添加他将停留的天数,我还有另一个字段,它是一个日期时间字段,他可以在其中选择入住日期。因此,我需要将入住日期与预期天数相加以获取新日期。我在做 odoov14。

EX:如果用户添加 3 天并且入住日期是 22/04/2018

然后我需要在新字段“expected_date”中获取 25/04/2018。

import datetime
from datetime import timedelta

class HotelAccommodation(models.Model):
    _name = 'accommodation.room'
    _description = 'Reception'
    _rec_name = 'name_sequence'


expected_days = fields.Integer(string='Expected days')
expected_date = fields.Datetime(string='Expected date')


@api.onchange('expected_days')
def onchange_next_date(self):
    if self.checkin_date:
        date = datetime.datetime.strptime(self.checkin_date,"%Y-%m-%d")
        expected_date = date + datetime.timedelta(days=self.expected_days)

我的错误

 in onchange_next_date
date = datetime.datetime.strptime(self.checkin_date,"%Y-%m-%d")
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/lenovo/odoo/odoo-14.0/odoo/http.py",line 639,in _handle_exception
return super(JsonRequest,self)._handle_exception(exception)
File "/home/lenovo/odoo/odoo-14.0/odoo/http.py",line 315,in _handle_exception
raise exception.with_traceback(None) from new_cause
TypeError: strptime() argument 1 must be str,not datetime.datetime

解决方法

就这样做

import datetime
from datetime import timedelta

class HotelAccommodation(models.Model):
    _name = 'accommodation.room'
    _description = 'Reception'
    _rec_name = 'name_sequence'


expected_days = fields.Integer(string='Expected days')
expected_date = fields.Datetime(string='Expected date')


@api.onchange('expected_days')
def onchange_next_date(self):
    if self.checkin_date:
        self.expected_date = self.checkin_date + timedelta(days=self.expected_days)