1
votes

I use below example for round time in odoo.

@api.one
@api.depends('start','finish','pause')
def total(self):
    for rec in self:
        time1 = datetime.strptime(rec.start, "%Y-%m-%d %H:%M:%S")
        time2 = datetime.strptime(rec.finish, "%Y-%m-%d %H:%M:%S")
        rec.total_time = round(((time2 - time1).seconds / float(60*60) - self.pause))

For example:

if start = 07:57:21 , finish = 16:25:36, pause = 1 get result 7 hours

if start = 07:57:34 , finish = 16:28:42, pause = 1 get result 8 hours

First and second time different is 3 minutes but in result that is one hours!

How change round if total time >= 7 hours 30 minutes 01 second I need result 8 in other solution 7.5 (7 hours and 30 minutes)

2
in other solution 7 or 7.5?? Do you want 7 or 7.5? - qvpham
round(7.5)==8 and round(7.4)==7==int(7.4) and round(7.6)==8==int(7.6+1) - khelili miliana
@julivico Sorry my mistake, I'm edit question 7 hours 30 minutes 01 second I need result 8 in other solution 7.5 (7 hours and 30 minutes) - Pointer
like that round(7.5001) = 8, round(7.4)=7, round(7.5)=7.5 ? - qvpham
@julivico Yes, I want this! - Pointer

2 Answers

3
votes

For "%Y-%m-%d %H:%M:%S" you can use DEFAULT_SERVER_DATETIME_FORMAT

from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT

For your problem you can use round(x, n). Example:

round(7.4, 0) = 7
round(7.5, 0) = 8
round(7.5, 1) = 7.5

Here you need n = 1 for 7.5 and n=0 for the 'standard' round. You can check 7.5 with ((7.5 - 0.5) % 1) == 0 and convert it from boolean to int directly with int()

The general solution is:

@api.one
@api.depends('start','finish','pause')
def total(self):
    for rec in self:
        time1 = datetime.strptime(rec.start, DEFAULT_SERVER_DATETIME_FORMAT)
        time2 = datetime.strptime(rec.finish, DEFAULT_SERVER_DATETIME_FORMAT)
        total_time = (time2 - time1).seconds / float(60*60) - self.pause
        rec.total_time = round(total_time, int(((total_time - 0.5) % 1) == 0))
1
votes
@api.one
@api.depends('start','finish','pause')
def total(self):
    for rec in self:
        time1 = datetime.strptime(rec.start, DEFAULT_SERVER_DATETIME_FORMAT)
        time2 = datetime.strptime(rec.finish, DEFAULT_SERVER_DATETIME_FORMAT)
        total_time = (time2 - time1).seconds / float(60*60) - self.pause
        total_time = 2*total_time
        if 2*total_time%1 <=0.5 :
            res = round(total_time)
        else :
            res = round(2*total_time)
        rec.total_time = res