Convert char to datetime odoo 9

て烟熏妆下的殇ゞ 提交于 2019-12-23 18:30:51

问题


I have two char fields, data import from excel or csv in odoo.

time_1= fields.Char(string = 'Time 1')
time_2= fields.Char(string = 'Time 2') 
result= fields.Float(string = 'Result Time 2 - Time 1')  #Need result 06:00

time_1 = 10:00:00, time_2 = 16:00:00 (data from external source)

How with @api.onchange('time_1', 'time_2') or @api.depends('time_1', 'time_2')

convert char to time and subtract time_2 - time_1 and put result in result field?


回答1:


It should be like that,

from datetime import datetime

@api.multi
@api.onchange('time_1', 'time_2') 
def onchange_time(self):
    for rec in self:
        time1 = datetime.strptime(rec.time1, "%Y-%m-%d %H:%M:%S")
        time2 = datetime.strptime(rec.time2, "%Y-%m-%d %H:%M:%S")
        rec.result = (time2 - time1).seconds / float(60*60)

Two datetime objects will return timedelta obect in result while you perform any arithmetic operations on it. timedelta has property while will give you difference in seconds, so you can convert that seconds to hours.

And then in view set

<field name="result" widget="float_time" />


来源:https://stackoverflow.com/questions/41148952/convert-char-to-datetime-odoo-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!