TheRedosan
TheRedosan

Reputation: 79

How to trasnform date to formatted string in a Odoo module?

have a Date field that is filled in with the current date. On the other hand, I have a calculated field that I need to be this date that has been generated, but with the format yyyymmddhhmmss using the autogenerated field. There is de class:

class incidencia(models.Model):
    _name = 'incidencias.incidencia'

    fecha_inicio = fields.Date(default=fields.Date.today, required=True)
    name = fields.Char(compute='_asignar_nombre', required=True)

    @api.depends('fecha_inicio')
    def _asignar_nombre(self):
        #¿?

Any ideas? I just started with Odoo and I'm not sure how to deal with the data types.

Upvotes: 2

Views: 4965

Answers (1)

Naglis Jonaitis
Naglis Jonaitis

Reputation: 2633

class incidencia(models.Model):
    _name = 'incidencias.incidencia'

    fecha_inicio = fields.Date(default=fields.Date.today, required=True)
    name = fields.Char(compute='_asignar_nombre', required=True)

    @api.depends('fecha_inicio')
    def _asignar_nombre(self):
        for record in self:
            record.name = fields.Date.from_string(
                record.fecha_inicio).strftime('%Y%m%d%H%M%S')

Note: as you have chosen Date instead of Datetime, you will get zeros for hours, minutes and seconds in the formatted name, as time information is not stored in a Date field. If you need to keep track of time as well, I would suggest to use Datetime. Note to change to odoo.fields.Datetime.from_string in the compute function if you decide to use Datetime.

Upvotes: 3

Related Questions