问题
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