You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # This module copyright (C) 2014 Savoir-faire Linux
  6. # (<http://www.savoirfairelinux.com>).
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. from datetime import datetime
  23. import logging
  24. _logger = logging.getLogger(__name__)
  25. import pytz
  26. from jinja2 import contextfilter
  27. from openerp.tools import (
  28. DEFAULT_SERVER_DATETIME_FORMAT as DTFMT,
  29. DEFAULT_SERVER_DATE_FORMAT as DFMT,
  30. )
  31. from openerp.addons.email_template import email_template
  32. @contextfilter
  33. def format_date(context, dtstr, new_format, tz=None):
  34. if not dtstr:
  35. return dtstr
  36. try:
  37. date = datetime.strptime(dtstr, DTFMT)
  38. except ValueError:
  39. # Maybe this is a date, not datetime
  40. date = datetime.strptime(dtstr, DFMT)
  41. if tz:
  42. tz_name = tz
  43. elif context.get("user") and context["user"].tz:
  44. tz_name = context["user"].tz
  45. else:
  46. tz_name = context.get("ctx", {}).get("tz")
  47. if tz_name:
  48. try:
  49. utc = pytz.timezone('UTC')
  50. context_tz = pytz.timezone(tz_name)
  51. utc_timestamp = utc.localize(date, is_dst=False) # UTC = no DST
  52. date = utc_timestamp.astimezone(context_tz)
  53. except Exception:
  54. _logger.debug("failed to compute context/client-specific timestamp, "
  55. "using the UTC value",
  56. exc_info=True)
  57. return date.strftime(new_format)
  58. email_template.mako_template_env.filters.update(
  59. format_date=format_date,
  60. )