## $Id$ ## ## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## """Datetimewidgets that are compatible with pytz. """ import datetime import pytz from zope.formlib.textwidgets import DatetimeWidget class PytzDatetimeWidget(DatetimeWidget): """pytz-conform, non-ambigous UTC datetimes. While the standard formlib datetime widget makes use of zope.datetime and creates also not too reliable (or ambigous) datetimes based on local servertime, this widget provides non-ambigous UTC datetimes with a pytz timezone (pytz.utc). Using this widget for datetime data we always get clean UTC datetimes compatible with other Python packages (as pytz is more wide-spread than zope.datetime). For datetimes in other timezones we compute the correct UTC value and store this. A way to help making sure, only UTC-based values go into the DB. From zope.datetime, however, we save the parser abilities to interpret even bizarre entered data as some datetime. """ def _toFieldValue(self, string): """Turn string into a UTC-based datetime. The TZ data is guaranteed to be pytz.utc. """ value = super(PytzDatetimeWidget, self)._toFieldValue(string) if not isinstance(value, datetime.datetime): return value if value.tzinfo is None: return pytz.utc.localize(value) return value.astimezone(pytz.utc)