Calculate total days since two dates in python openerp

I have three fields start_date, end_dateand total_days.

If I enter the field start_dateand end_dateit should automatically display total_days.

This is my function that does not work.

<field name="start_date" on_change="get_number_of_days(start_date,end_date)"/>
<field name="end_date" on_change="get_number_of_days(end_date,start_date)"/>
<field name="total_days" />

def get_number_of_days(self, cr, uid, ids, start_date, end_date):
        """Returns a float equals to the timedelta between two dates given as string."""
        result = self.browse(cr, uid, ids)
        if (end_date and start_date) and (start_date <= end_date):
            DATETIME_FORMAT = "%d/%m/%Y %H:%M:%S"
            from_dt = datetime.datetime.strptime(start_date, DATETIME_FORMAT)
            to_dt = datetime.datetime.strptime(end_date, DATETIME_FORMAT)
            timedelta = to_dt - from_dt
            diff_day = timedelta.days + float(timedelta.seconds) / 86400
            result['value']['total_days'] = round(math.floor(diff_day))+1
        return result 

Is there any other method? or what could be the problem

+4
source share
3 answers

Section:

        diff_day = timedelta.days + float(timedelta.seconds) / 86400
        result['value']['total_days'] = round(math.floor(diff_day))+1

pretty much not required since it datetime.timedeltaalready has the number of whole days as a value timedelta.days- I suspect your problem is that you are not converting to a try string:

         result['value']['total_days'] = str(timedelta.days)

, strptime , . .

+2

( ), ( /), :

if (end_date and start_date) and (start_date <= end_date):
    # ...

datetime-objects , .

+2

Thanks,

I wrote a new function for this, which helped give common days:

def _get_days(self, cr, uid, ids, field_name, arg ,context=None):
        res = {}
        fmt = '%Y-%m-%d'
        for object in self.browse(cr, uid, ids, context=context):
            res[object.id] = {'total_days':0, } 
            from_date = object.start_date 
            to_date = object.end_date
            d1 = datetime.strptime(from_date, fmt)
            d2 = datetime.strptime(to_date, fmt)
            daysDiff = str((d2-d1).days+1)
            res[object.id]['total_days'] = daysDiff
            return res

'start_date': fields.date('Start Date', required=True),
        'end_date': fields.date('End Date', required=True),
        'total_days': fields.function(_get_days, string="Diff days", multi='sums', store=True),
0
source

Source: https://habr.com/ru/post/1620272/


All Articles