Basit
Basit

Reputation: 17214

How to display different date formats in Odoo datetime fields?

Currently the date format on our Odoo CRM looks like 11/20/2017 13:03:41 but I want to display the format to July 3rd 3:00PM and on another place show as 3 Jul 3:00PM

We show this field in the form

<field name="pickup_time"/>

I have searched a lot to find how to change the format, but It's mainly to change in the local settings and it's permanently one setting for everywhere. Which would not solve of what we want, like having two different format for different places.

Upvotes: 5

Views: 16754

Answers (1)

ChesuCR
ChesuCR

Reputation: 9670

Along Odoo the default constant date format used is DEFAULT_SERVER_DATETIME_FORMAT. This is defined in the file misc.py

DEFAULT_SERVER_DATE_FORMAT = "%Y-%m-%d"
DEFAULT_SERVER_TIME_FORMAT = "%H:%M:%S"
DEFAULT_SERVER_DATETIME_FORMAT = "%s %s" % (
    DEFAULT_SERVER_DATE_FORMAT,
    DEFAULT_SERVER_TIME_FORMAT)

So if you declare the field like the following code then that constant is going to be used:

pickup_time = fields.Datetime(
    string="Pickup time",
)

So if you want to use another format you can create a computed field with that custom format. You need to use some date functions: strftime (object to string) and strptime (string to object). The formats codes are explained almost at the bottom of this python documentation page

from datetime import datetime
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT

[...]

pickup_time_formated = fields.Char(   # it is going to be a readonly field
    string='Pickup time formated',
    compute='_compute_pickup_time_formated'
)

@api.multi
@api.depends('pickup_time')
def _compute_pickup_time_formated(self):
    for record in self:
        date = record.pickup_time
        date_obj = datetime.strptime(date, DEFAULT_SERVER_DATETIME_FORMAT)   # to convert it in a date object

        v = date_obj.day % 10           # to get the remainder of the operation
        if v == 1:
            ordinal_suffix = 'st'
        elif v == 2:
            ordinal_suffix = 'nd'
        elif v == 3:
            ordinal_suffix = 'rd'
        else:
            ordinal_suffix = 'th'

        # format 'July 3rd 3:00PM'
        record.pickup_time_formated = datetime.strftime(date_obj, '%B %d' + ordinal_suffix + ' %I:%M %p')

        # format '3 Jul 3:00PM'
        # record.pickup_time_formated = datetime.strftime(date_obj, '%d %b %I:%M %p'),

And then you can show the new fields in the xml form:

<field name="pickup_time_formated"/>

Upvotes: 4

Related Questions