Skip to Content
Menu
This question has been flagged
1 Reply
1375 Views

How can I calculate total hours between two dates. here I have to select start date and end date. and every day an employee work 8 hours per day.  how can I calculate total hours between these two dates. Example If I select two dates date from: 11/21/2022 and date to:11/22/2022. this two dates total hours is 16hours. and date need to count without holiday how can I do that. Please help me.

here is two fileds:

 

start_date = fields.Date(string='Start Date')
total_hours = fields.Float('Total Hours', compute='_compute_hours')
date_deadline = fields.Date(string='Deadline')
Avatar
Discard
Best Answer

Hello Nahid Jawad Angon
We can calculate hours between two dates by using below code.

from datetime import timedelta

Please Find Code in Comment.

I Hope this will help you. 

Thanks & Regards,
Email: odoo@aktivsoftware.com
Skype: kalpeshmaheshwari

Avatar
Discard

def _compute_hours(self):
for rec in self:
test_date1 = rec.start_date
test_date1 = rec.date_deadline

dates = (test_date1 + timedelta(idx + 1)
for idx in range((test_date2 - test_date1).days))

# We'll only consider working days
rec.total_hours = sum(8 for day in dates if (day.weekday() < 5))

Author

Its showing an error:
Traceback (most recent call last):
File "D:\Odoo\odoo-14.0\odoo\http.py", line 641, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "D:\Odoo\odoo-14.0\odoo\http.py", line 317, in _handle_exception
raise exception.with_traceback(None) from new_cause
TypeError: unsupported operand type(s) for -: 'datetime.date' and 'bool'

Sorry it was my fault, we have defined the test_date1 variable 2 times. we just need to replace 'test_date1 = rec.date_deadline' with 'test_date2 = rec.date_deadline'.