Skip to Content
Menu
You need to be registered to interact with the community.
This question has been flagged
7 Odgovori
3166 Prikazi

Hi,

i'm trying to build a function that gives me the difference between two date-times, but it doesn't work and nothing changes when changing the dates

start_time = fields.Datetime(string='Start Time', default=fields.Datetime.now)
end_time = fields.Datetime(string='End Time', default=fields.Datetime.now)

@api.onchange('start_time', 'end_time')
def _get_time(self):
t1 = datetime.datetime.strptime(self.start_time, '%Y-%m-%d %H:%M:%S')
t2 = datetime.datetime.strptime(self.end_time, '%Y-%m-%d %H:%M:%S')
time_diff = (t2 - t1)
self.unit_amount = time_diff

can anyone tell me the wrong in my code?
Thanks
Avatar
Opusti
Best Answer

Hi, Ali


In Odoo 13 you don't need to use "strptime".

You can simply need subtract directly from fields. You can refer to the below code,

@api.onchange('start_time', 'end_time')
def _get_time(self):
    self.unit_amount = int(self.end_time - self.start_time)
For Odoo 12 you can use below code, (Updated My Answer for Odoo 12.0)
from datetime import datetime, timedelta
@api.onchange('start_time', 'end_time')
def _get_time(self):
    date_format = '%Y-%m-%d %H:%M:%S'
    t1 = datetime.strptime(str(self.start_time), date_format)
    t2 = datetime.strptime(str(self.end_time), date_format)
    time_diff = (t2 - t1)
    self.unit_amount = float(time_diff.seconds)
Thanks,
Ashish Singh (Team Lead)
Webkul Software Private Limited
Avatar
Opusti
Avtor

Thanks but I'm using Odoo 12

Hi, Ali

For Odoo 12 Kindly follow the below code,

from datetime import datetime, timedelta

@api.onchange('start_time', 'end_time')

def _get_time(self):

date_format = '%Y-%m-%d %H:%M:%S'

t1 = datetime.strptime(str(self.start_time), date_format)

t2 = datetime.strptime(str(self.end_time), date_format)

time_diff = (t2 - t1)

self.unit_amount = float(time_diff.seconds)

Thanks.

Ashish Singh

Hi, Ali

If field is float type then you needs to find total second,days etc. via timedelta object like code given my last post.

Best Answer

Hi,

I think you must pass a string instead of datetime when using strptime.Can you try after rewriting the code like below

@api.onchange('start_time', 'end_time')
def _get_time(self):
t1 = datetime.datetime.strptime(str(self.start_time), '%Y-%m-%d %H:%M:%S')
t2 = datetime.datetime.strptime(str(self.end_time), '%Y-%m-%d %H:%M:%S')
time_diff = (t2 - t1)
self.unit_amount = time_diff

Regards

Avatar
Opusti
Avtor

Thanks

i got this error when i used str():

TypeError: float() argument must be a string or a number, not 'datetime.timedelta'

Hi,

Please check your field type of unit_amount

currently the time_diff will be of type datetime.timedelta

you can extract the required details from time_diff and allocate to unit_amount according to the field type of the unit_amount