Odoo 13类型错误:strptime()参数1必须是str,而不是datetime.dateE



class出生日期年龄(models.Model(:

_inherit = "hr.employee"
birthday = fields.Date(string="DOB")
age = fields.Integer(string="Age")
@api.onchange('birthday')
def _onchange_birth_date(self):
"""Updates age field when birth_date is changed"""
if self.birthday:
d1 = datetime.strptime(self.birthday, "%Y-%m-%d").date()
d2 = date.today()
self.age = relativedelta(d2, d1).years

错误:


Odoo Server Error
Traceback (most recent call last):
File "/odoo/odoo-server/odoo/http.py", line 619, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/odoo/odoo-server/odoo/http.py", line 309, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File "/odoo/odoo-server/odoo/tools/pycompat.py", line 14, in reraise
raise value
File "/odoo/odoo-server/odoo/http.py", line 664, in dispatch
result = self._call_function(**self.params)
File "/odoo/odoo-server/odoo/http.py", line 345, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/odoo/odoo-server/odoo/service/model.py", line 93, in wrapper
return f(dbname, *args, **kwargs)
File "/odoo/odoo-server/odoo/http.py", line 338, in checked_call
result = self.endpoint(*a, **kw)
File "/odoo/odoo-server/odoo/http.py", line 910, in __call__
return self.method(*args, **kw)
File "/odoo/odoo-server/odoo/http.py", line 510, in response_wrap
response = f(*args, **kw)
File "/odoo/odoo-server/addons/web/controllers/main.py", line 1320, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/odoo/odoo-server/addons/web/controllers/main.py", line 1312, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/odoo/odoo-server/odoo/api.py", line 387, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "/odoo/odoo-server/odoo/api.py", line 374, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/odoo/odoo-server/odoo/models.py", line 6070, in onchange
record._onchange_eval(name, field_onchange[name], result)
File "/odoo/odoo-server/odoo/models.py", line 5871, in _onchange_eval
method_res = method(self)
File "/odoo/odoo-server/addons/hr/models/hr_employee.py", line 87, in _onchange_birth_date
('married', 'Married'),
TypeError: strptime() argument 1 must be str, not datetime.dateE

自Odoo 11以来,日期和日期时间类型的字段是日期或日期时间类型对象,不再是字符串
所以你不必使用这个:

d1 = datetime.strptime(self.birthday, "%Y-%m-%d").date()

只需使用此选项:
d1 = self.birthday

在这里查看Python日期时间模块文档。

正如您的错误所示,strptime方法的第一个参数应该是格式化字符串。所以,只需恢复您的参数如下。

d1 = datetime.strptime("%Y-%m-%d", self.birthday).date()
d1 = datetime.strptime(str(self.birthday), "%Y-%m-%d").date()

self.birthday的类型已经是Date,所以不需要使用DateTime模块来转换它。

您可以将代码缩减为一行:

self.age = relativedelta(fields.Date.today(), self.birthday).years

最新更新