Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

1

HOW TO CALCULATE DATE difference using datetime

By
Annadurai
on 6/6/16, 5:08 AM 486 views

from_date=fields.Date(string="Register date")

final_date=fields.Date(string="Last date")

total_days=fields.Integer(string="TOTAL DAYS")


@api.onchange('total_days','from_date','total_days')

def calculate_date(self):

 d1=datetime.strptime(str(self.from_date),'%Y-%m-%d') 

d2=datetime.strptime(str(self.final_date),'%Y-%m-%d')

d3=d2-d1

self.total_days=str(d3) . it doesnt work

2

Pawan

--Pawan--
1267
| 4 3 5
Hyderabad, India
--Pawan--


Pawan
On 6/6/16, 5:51 AM

Annudarai,

After using strptime you will get a datetime object, and once you perform any operation(+, -, /, etc..) on that object, what u will get is a timedelta object..

SO, as you have not provided any result(error or value of d3 you are getting), i can recommend you to check these things.

  • Are the values set for self.from_date and self.end_date

  • what are u getting after d3 = d2-d1, is it a 'timedelta' object ? (you can use type(d3) to get its object type)

  • if above are yes... then use self.total_days = d3.days (days is an attribute of timedelta object to get no of days in integer)

    Hope it will help you...

UPDATED:

Here your answer...

    from_date=fields.Date(string="Register date")
final_date=fields.Date(string="Last date")
total_days=fields.Integer(string="TOTAL DAYS")

@api.onchange('from_date', 'final_date','total_days')
def calculate_date(self):
if self.from_date and self.final_date:
d1=datetime.strptime(str(self.from_date),'%Y-%m-%d')
d2=datetime.strptime(str(self.final_date),'%Y-%m-%d')
d3=d2-d1
self.total_days=str(d3.days)

thank you.

Annadurai
on 6/6/16, 8:56 AM
3
kirubanidhi
On 6/9/16, 2:49 AM

hai annadhurai,

     please specify a header file named as

from datetime import datetime

instead of your code replace this code is working perfectly

d1 = datetime.strptime(self.date_start,"%Y-%m-%d")

d2 = datetime.strptime(self.date_end,"%Y-%m-%d")

self.no_of_days=abs((d2 - d1).days)

The method abs() returns absolute value of x - the (positive) distance between x and zero

print "abs(-45) : ", abs(-45)
output:
abs(-45) : 45

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

1 follower(s)

Stats

Asked: 6/6/16, 5:08 AM
Seen: 486 times
Last updated: 6/9/16, 3:01 AM