:param datetime timestamp: optional datetime value to use instead of
the current date and time (must be a
datetime, regular dates can't be converted
- between timezones.)"""
+ between timezones.)
+ :param dict context: the 'tz' key in the context should give the
+ name of the User/Client timezone (otherwise
+ UTC is used)
+ :rtype: str
+ """
today = timestamp or DT.datetime.now()
context_today = None
if context and context.get('tz'):
try:
utc = pytz.timezone('UTC')
context_tz = pytz.timezone(context['tz'])
- utc_today = utc.localize(today, is_dst=False)
+ utc_today = utc.localize(today, is_dst=False) # UTC = no DST
context_today = utc_today.astimezone(context_tz)
except Exception:
_logger.debug("failed to compute context/client-specific today date, "
return DT.datetime.now().strftime(
tools.DEFAULT_SERVER_DATETIME_FORMAT)
+ @staticmethod
+ def context_timestamp(cr, uid, timestamp, context=None):
+ """Returns the given timestamp converted to the client's timezone.
+ This method is *not* meant for use as a _defaults initializer,
+ because datetime fields are automatically converted upon
+ display on client side. For _defaults you :meth:`fields.datetime.now`
+ should be used instead.
+
+ :param datetime timestamp: naive datetime value (expressed in UTC)
+ to be converted to the client timezone
+ :param dict context: the 'tz' key in the context should give the
+ name of the User/Client timezone (otherwise
+ UTC is used)
+ :rtype: datetime
+ :return: timestamp converted to timezone-aware datetime in context
+ timezone
+ """
+ assert isinstance(timestamp, DT.datetime), 'Datetime instance expected'
+ if context and context.get('tz'):
+ try:
+ utc = pytz.timezone('UTC')
+ context_tz = pytz.timezone(context['tz'])
+ utc_timestamp = utc.localize(timestamp, is_dst=False) # UTC = no DST
+ return utc_timestamp.astimezone(context_tz)
+ except Exception:
+ _logger.debug("failed to compute context/client-specific timestamp, "
+ "using the UTC value",
+ exc_info=True)
+ return timestamp
+
class time(_column):
_type = 'time'
_deprecated = True