Search Here

Playing with Date field in Odoo

 In this article, you will learn how to use and convert Odoo date field (which is in string format by default) into a python date object using datetime package provided by the python built-in library.

How to use and manipulate the Date field in Odoo

How to use and manipulate the Date field in Odoo

To create a date field in Odoo we will use fields. Date, the attribute type of this field in PostgreSQL is a date, but when we print this field value it gives a date in string. To manipulate and perform some action on that date field we need to convert this date value from a string into a date object. To do that we will use a python built-in package named datetime.


from datetime import datetime, timedelta, date
class some_model(models.Model):
_name = 'some.model'
# creating date field in odoo class
date_start = fields.Date(string="Start Date")
@api.one
def button_click(self):
# converting string date value into python date object
date_start = datetime.strptime(self.date_start, '%Y-%m-%d').date()

Get the First Date of every month between two dates in python

In this part, you will learn how to extract the first date of every month provided by two dates (start and end date). In Odoo date field stores values in string format. To extract the first date of each month we need to convert the string date into a python date object.

from datetime import datetime, timedelta, date
class some_model(models.Model):
_name = 'some.model'
# creating date field in odoo class
date_start = fields.Date(string="Start Date")
date_end = fields.Date(string="End Date")
@api.multi
def calc_first_date_of_month(self,from_date, end_date, day=1):
"""Produce a date for every month from start until end"""
start = from_date.year * 12 + (from_date.month - 1)
end = end_date.year * 12 + (end_date.month - 1)
if end_date.day > day:
# end date is past the reference day, include the reference
# date in the output
end += 1
# generate the months, just a range from start to end
for ordinal in range(start, end):
yield date(ordinal // 12, (ordinal % 12) + 1, day)
@api.one
def button_click(self):
# converting string date value into python date object
date_start = datetime.strptime(self.date_start, '%Y-%m-%d').date()
date_end = datetime.strptime(self.date_end, '%Y-%m-%d').date()
list_of_date = list(self.calc_first_date_of_month(date_start, date_end))
print('***',list_of_date)

Post a Comment

0 Comments