This question has been flagged
3 Replies
4211 Views

How to compute the year only? using fields.date i want to subtract the year in other field. could it be possible?

Avatar
Discard
Best Answer

from dateutil.relativedelta import relativedelta
from datetime import datetime
from openerp import tools

end_date = datetime.strptime('10-02-2015', tools.DEFAULT_SERVER_DATE_FORMAT) # '10-02-2015' - Your date field
begin_date = datetime.strptime('10-02-2010', tools.DEFAULT_SERVER_DATE_FORMAT) # '10-02-2010' - Your date field
difference = relativedelta(end_date, begin_date).years
print(difference) # 5

Avatar
Discard
Author Best Answer

from dateutil.relativedelta import relativedelta
from datetime import datetime
from openerp import tools

end_date = datetime.strptime('10-02-2015', tools.DEFAULT_SERVER_DATE_FORMAT) # '10-02-2015' - Your date field
begin_date = datetime.strptime('10-02-2010', tools.DEFAULT_SERVER_DATE_FORMAT) # '10-02-2010' - Your date field
difference = relativedelta(end_date, begin_date).years
print(difference) # 5

==>regarding with your answer i try this and its error. when i add it in view.xml. what should i do?

   

Avatar
Discard

This is the sample calculation code. Put it in a function and store the result in the field you want. You can call the function via onchange or make the field as functional field.

Best Answer

Try this:

from openerp import tools
import datetime

dt = datetime.datetime.strptime(self.my_field_date, tools.DEFAULT_SERVER_DATE_FORMAT)
self.year = dt.strftime('%Y')  # long year
self.year = dt.strftime('%y') # short year

 

Avatar
Discard