Skip to Content
Menu
This question has been flagged
2 Replies
14864 Views

I try to add some minutes and hours to a Datetime field. Somehow I get a datatype missmatch and I can't figure out what is wrong. Everything that I try gets an error:

File "/opt/odoo/custom/....... in onchange_duration_hrs
end_time = (self.start_datetime + timedelta(hours=hour, minutes=minute))  
TypeError: coercing to Unicode: need string or buffer, datetime.timedelta found


File "/opt/odoo/custom/addons..... line 182, in onchange_duration_hrs
end_time = (self.start_datetime + datetime.timedelta(hours=hour, minutes=minute))
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'


If I just change the field self.start_datetime to datetime.now() the function works correct. 

start_datetime = fields.Datetime(string='Start DateTime')

end_time = (datetime.now() + datetime.timedelta(hours=hour, minutes=minute))

Any hint would be welcome?

 

Avatar
Discard
Author Best Answer

Thanks to Yvans post I have now a solution (his code did cause still an error):

@api.multi  # getting integer out of float from widget "float_time" 
def _float_time_convert(self, float_val):
factor = float_val < 0 and -1 or 1
val = abs(float_val)
return (factor * int(math.floor(val)), int(round((val % 1) * 60)))


@api.one  # Getting the Stop DateTime
@api.onchange('start_datetime', 'toggle')
def _get_stop_time_hrs(self):
    if not (self.start_datetime and self.duration) or self.allday is True:
   return value
   start_time = datetime.strptime(self.start_datetime, DEFAULT_SERVER_DATETIME_FORMAT)
   hour, minute = self._float_time_convert(self.duration)
   end_time = (start_time + timedelta(hours=hour,   minutes=minute)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
    self.stop_datetime = end_time

But I still get an strftime error when I try to get the result back to datetime field with return value from method (without onchange api ofcourse)?

 return end_time




Avatar
Discard
Best Answer

Hi Lucas,

the problem is the type of self.start_datetime: it's a string and not as expected a datetime object. You have to convert the string to a datetime object before you add a timedelta. To to this, use the fields.Datetime.from_string method as shown below


end_time = fields.Datetime.from_string(self.start_datetime) + datetime.timedelta(hours=hours, minutes=minute)

Best regards

Yvan

Avatar
Discard
Related Posts Replies Views Activity
4
Oct 24
9459
1
Jul 23
1870
4
Dec 22
7972
2
Apr 21
2264
1
Oct 18
3724