odoo-local/docs/Odoo development cheatsheet.md

1.3 KiB

Odoo development cheatsheet

Datetime & Timezones

  • All datetime are stored in UTC in database
  • fields.Datetime are in UTC. They are only displayed in the user's timezone

Fetching data with specific timezone

This is tricky. If for whatever reason the datetime value cannot be send directly from the UI (and so be automatically converted), the value has to be converted in the code.

import pytz


## Get the timezone first. This is retrieved from context then user, then default. Can be set in another way
timezone = pytz.timezone(self.env.context.get('tz') or self.env.user.tz or 'UTC')
## Create a localized datetime from the date source
date_tz = timezone.localize(fields.Datetime.from_string("1988-05-16 16:55:00"))

## Now get an UTC datetime from the localized one
start = date_tz.astimezone(pytz.timezone('UTC'))
## If needed, set up an end date from the starting one
end = start + relativedelta(years=36)

# Retrieve the data 
awesome_guy_ids = self.env['sale.report'].search(['&',
   ('date', '>=', start),
    ('date', '<', end),
])

Display date on context timezome

If for whatever reason (reports, typically), the date is displayed in UTC instead of the contaxt timezone, use :

fields.Datetime.context_timestamp(self, date)