From 46c70fac7ac7276b623d5356c1edc18fd8302c88 Mon Sep 17 00:00:00 2001 From: Vincent Vinet Date: Fri, 22 Aug 2014 13:17:46 -0400 Subject: [PATCH] handle timezones --- email_template_dateutil/__openerp__.py | 5 +++- email_template_dateutil/email_template.py | 32 ++++++++++++++++++++--- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/email_template_dateutil/__openerp__.py b/email_template_dateutil/__openerp__.py index d2b65fee0..2e83caad0 100644 --- a/email_template_dateutil/__openerp__.py +++ b/email_template_dateutil/__openerp__.py @@ -32,7 +32,10 @@ 'description': """ This module adds an extra filter in email templates: -format_date(format) : parses and formats a date or datetime string +format_date(format, tz=tzname) : parses and formats a date or datetime string. + Optional parameter tz allows specifying the timezone to use. Otherwise, the + user's timezone or server timezone will be used. If none are found, time is + left in UTC Example: ${ object.date_field|format_date('%m/%d/%Y') } diff --git a/email_template_dateutil/email_template.py b/email_template_dateutil/email_template.py index abc3fa194..b8660ecf6 100644 --- a/email_template_dateutil/email_template.py +++ b/email_template_dateutil/email_template.py @@ -21,6 +21,11 @@ ############################################################################## from datetime import datetime +import logging +_logger = logging.getLogger(__name__) + +import pytz +from jinja2 import contextfilter from openerp.tools import ( DEFAULT_SERVER_DATETIME_FORMAT as DTFMT, @@ -29,17 +34,36 @@ from openerp.tools import ( from openerp.addons.email_template import email_template -def format_date(dtstr, new_format): +@contextfilter +def format_date(context, dtstr, new_format, tz=None): if not dtstr: return dtstr try: - return datetime.strptime(dtstr, DTFMT).strftime(new_format) + date = datetime.strptime(dtstr, DTFMT) except ValueError: # Maybe this is a date, not datetime - pass + date = datetime.strptime(dtstr, DFMT) + + if tz: + tz_name = tz + elif context.get("user") and context["user"].tz: + tz_name = context["user"].tz + else: + tz_name = context.get("ctx", {}).get("tz") + + if tz_name: + try: + utc = pytz.timezone('UTC') + context_tz = pytz.timezone(tz_name) + utc_timestamp = utc.localize(date, is_dst=False) # UTC = no DST + date = utc_timestamp.astimezone(context_tz) + except Exception: + _logger.debug("failed to compute context/client-specific timestamp, " + "using the UTC value", + exc_info=True) - return datetime.strptime(dtstr, DFMT).strftime(new_format) + return date.strftime(new_format) email_template.mako_template_env.filters.update(