source: main/waeup.kofa/trunk/src/waeup/kofa/widgets/datetimewidget.py @ 16293

Last change on this file since 16293 was 12110, checked in by Henrik Bettermann, 10 years ago

svn propset svn:keywords "Id"

  • Property svn:keywords set to Id
File size: 3.5 KB
Line 
1## $Id: datetimewidget.py 12110 2014-12-02 06:43:10Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""Datetimewidgets that are compatible with pytz.
19"""
20import datetime
21import pytz
22from zope.component import queryUtility
23from zope.datetime import parseDatetimetz
24from zope.datetime import DateTimeError
25from zope.formlib.i18n import _
26from zope.formlib.interfaces import ConversionError
27from zope.formlib.textwidgets import DatetimeWidget
28from waeup.kofa.utils.helpers import to_timezone
29from waeup.kofa.interfaces import IKofaUtils
30
31class _DummyUtils(object):
32    tzinfo = pytz.utc
33
34# A fallback, if no IKofaUtils can be found
35_DUMMY_UTILS = _DummyUtils()
36
37class PytzDatetimeWidget(DatetimeWidget):
38    """pytz-conform, non-ambigous UTC datetimes.
39
40    While the standard formlib datetime widget makes use of
41    zope.datetime and creates also not too reliable (or ambigous)
42    datetimes based on local servertime, this widget provides
43    non-ambigous UTC datetimes with a pytz timezone (pytz.utc).
44
45    Using this widget for datetime data we always get clean UTC
46    datetimes compatible with other Python packages (as pytz is more
47    wide-spread than zope.datetime).
48
49    For datetimes in other timezones we compute the correct UTC value
50    and store this. A way to help making sure, only UTC-based values
51    go into the DB.
52
53    For datetimes without any timezone set, we interpret the input to
54    be meant as local app-time. I.e. if application TZ is
55    ``Africa/Lagos``, we assume that a string like '2012-02-01 12:13'
56    (apparently not providing TZ info) was meant as 12:13 h Lagos
57    time.
58
59    From zope.datetime, however, we save the parser abilities to
60    interpret even bizarre entered data as some datetime.
61    """
62    def _toFieldValue(self, string):
63        """Turn string into a UTC-based datetime.
64
65        The TZ data is guaranteed to be pytz.utc.
66
67        """
68        # In import files we can use the hash symbol at the end of a
69        # datetime and date strings to avoid annoying automatic date
70        # transformation by Excel or Calc.
71        string = string.strip('#')
72        if string == self._missing:
73            return self.context.missing_value
74        else:
75            try:
76                # Different to original implementation we do not
77                # automatically request local server time if no TZ was
78                # set in `string`. In this case we want a datetime with
79                # tzinfo set to `None` instead.
80                value = parseDatetimetz(string, local=False)
81            except (DateTimeError, ValueError, IndexError), v:
82                raise ConversionError(_("Invalid datetime data"), v)
83
84        if not isinstance(value, datetime.datetime):
85            return value
86        if value.tzinfo is None:
87            utils = queryUtility(IKofaUtils, default=_DUMMY_UTILS)
88            value = utils.tzinfo.localize(value)
89        return value.astimezone(pytz.utc)
Note: See TracBrowser for help on using the repository browser.