This question has been flagged

UPDATE: Changed the example to use single timezone case

I'm trying to understand the implementation of context_today (in v7, v8, v9 versions), which I quote below:

    def context_today(model, cr, uid, context=None, timestamp=None):
 today = timestamp or DT.datetime.now()
       context_today = None
if context and context.get('tz'):
tz_name = context['tz']
else:
user = model.pool['res.users'].browse(cr, SUPERUSER_ID, uid)
tz_name = user.tz
if tz_name:
try:
utc = pytz.timezone('UTC')
context_tz = pytz.timezone(tz_name)
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, "
"using the UTC value for `today`",
exc_info=True)
return (context_today or today).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)

IMHO the code:

today = timestamp or DT.datetime.now()

will set today to current timestamp at the server's timezone (for example, 'Asia/Bangkok' (GMT+8)) if timestamp is not given, which is the case most of the time since context_today is used a lot in defaults.

If the user has it's timezone set to 'Asia/Bangkok' (GMT+8), then the code within "if tz_name" will be executed.  The part:

utc_today = utc.localize(today, is_dst=False) # UTC = no DST

will set utc_today to the same time as today but with the timezone removed and changed to 'UTC'.  Meaning that if today is 9 Sep 2016 17:00, then utc_today will be 9 Sep 2016 17:00 at UTC (although it should be 9 Sep 2016 10:00 AM UTC in actuality).

The code:

context_today = utc_today.astimezone(context_tz)

will make context_today to be 10 Sep 2016 00:00 AM and returned as 10 Sep 2016, whereas the time should be 9 Sep 2016 17:00 or 9 Sep 2016.

Is it the intended behaviour?  As if it assumes that the server will be operating at UTC timezone?  Isn't it better to use DT.datetime.utcnow() instead?

Also, is the User's Preference Timezone has any bearing at all to the system's behaviour?  I've also tested various value set of User's Preference Timezone on the "write" of fields of time datetime.  It assumes that the given value is set to be at the server's timezone, not User's Preference Timezone.

Avatar
Discard