Skip to Content
Menu
This question has been flagged
1 Reply
5830 Views

Guys, I would like to have in my module start date and end date set automatically and I have but both st_date and en_date is set "today":

I need:

end date = today

start date = 30 days before today (approximately a month before end date)

code i'm using :

 def _days_between(self, cr, uid, ids, field_name, arg, context=None):

res = {}

for cur_data in self.browse(cr, uid, ids, context=context):

st_date = datetime.strptime(cur_data.st_date, "%Y-%m-%d")

en_date = datetime.strptime(cur_data.en_date, "%Y-%m-%d")

res[cur_data.id] = abs((en_date - st_date).days)

return res

def _weeks_between(self, cr, uid, ids, field_name, arg, context=None):

res = {}

for cur_data in self.browse(cr, uid, ids, context=context):

st_date = datetime.strptime(cur_data.st_date, "%Y-%m-%d")

en_date = datetime.strptime(cur_data.en_date, "%Y-%m-%d")

week_day1 = (st_date - timedelta(days=st_date.weekday()))

week_day2 = (en_date - timedelta(days=en_date.weekday()))

res[cur_data.id] = (week_day2 - week_day1).days / 7

return res

def _months_between(self, cr, uid, ids, field_name, arg, context=None):

res = {}

for cur_data in self.browse(cr, uid, ids, context=context):

st_date = datetime.strptime(cur_data.st_date, "%Y-%m-%d")

en_date = datetime.strptime(cur_data.en_date, "%Y-%m-%d")

res[cur_data.id] = abs((en_date - st_date).days) / 30

return res


_columns = {

'product': fields.one2many('product.data','check_id', string="Product"),

'location_id': fields.many2one('stock.location','location'),

'st_date': fields.date('Start date'),

'en_date': fields.date('End date'),

'wr_date': fields.char('Date'),

'nod': fields.function(_days_between, type='integer', string='NoD'),

'now': fields.function(_weeks_between, type='integer', string='NoW'),

'nom': fields.function(_months_between, type='integer', string='NoM'),

}

_defaults = {

'st_date': lambda *a: time.strftime('%Y-%m-%d'),#30 days before end date

'en_date': lambda *a: time.strftime('%Y-%m-%d'),

'location_id': _get_def_loc,

}

How to set defaults?

Avatar
Discard
Best Answer

use timedelta as follows

from datetime import datetime, timedelta  
....
_defaults = {
.....
'st_date':lambda *a: datetime.strftime(datetime.now()-timedelta(days=30) ,'%Y-%m-%d'),
....
}

this will give you the result you requested

Avatar
Discard