Skip to Content
Menu
This question has been flagged
3 Replies
15286 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

Avatar
Discard
Best Answer

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)

Avatar
Discard
Author

thank you.

@annudarai How can i calculate the time, as i need to give the starting "Datetime" and "closing Datetime" and in result i need "Total hours"

Best Answer

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

Avatar
Discard