[8198] | 1 | ## $Id$ |
---|
| 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 | """ |
---|
| 20 | import datetime |
---|
| 21 | import pytz |
---|
| 22 | from zope.formlib.textwidgets import DatetimeWidget |
---|
| 23 | |
---|
| 24 | class PytzDatetimeWidget(DatetimeWidget): |
---|
| 25 | """pytz-conform, non-ambigous UTC datetimes. |
---|
| 26 | |
---|
| 27 | While the standard formlib datetime widget makes use of |
---|
| 28 | zope.datetime and creates also not too reliable (or ambigous) |
---|
| 29 | datetimes based on local servertime, this widget provides |
---|
| 30 | non-ambigous UTC datetimes with a pytz timezone (pytz.utc). |
---|
| 31 | |
---|
| 32 | Using this widget for datetime data we always get clean UTC |
---|
| 33 | datetimes compatible with other Python packages (as pytz is more |
---|
| 34 | wide-spread than zope.datetime). |
---|
| 35 | |
---|
| 36 | For datetimes in other timezones we compute the correct UTC value |
---|
| 37 | and store this. A way to help making sure, only UTC-based values |
---|
| 38 | go into the DB. |
---|
| 39 | |
---|
| 40 | From zope.datetime, however, we save the parser abilities to |
---|
| 41 | interpret even bizarre entered data as some datetime. |
---|
| 42 | """ |
---|
| 43 | def _toFieldValue(self, string): |
---|
| 44 | """Turn string into a UTC-based datetime. |
---|
| 45 | |
---|
| 46 | The TZ data is guaranteed to be pytz.utc. |
---|
| 47 | |
---|
| 48 | """ |
---|
| 49 | value = super(PytzDatetimeWidget, self)._toFieldValue(string) |
---|
| 50 | if not isinstance(value, datetime.datetime): |
---|
| 51 | return value |
---|
| 52 | if value.tzinfo is None: |
---|
| 53 | return pytz.utc.localize(value) |
---|
| 54 | return value.astimezone(pytz.utc) |
---|