Last active
December 18, 2015 12:49
-
-
Save Flushot/5785962 to your computer and use it in GitHub Desktop.
Factory method that creates an aware DateTime column (includes timezone info and automatically converts). Works with MySQL dialects, which only support naive datetime types.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import datetime | |
| from dateutil import tz | |
| from sqlalchemy import types | |
| from naive_aware import isAware, makeAware, makeNaive | |
| def AwareDateTime(tz=None, localtz=tz.tzlocal()): | |
| if tz is None: | |
| tz = tz.tzutc() | |
| elif isinstance(tz, str): | |
| tz = tz.gettz(tz) | |
| class AwareDateTimeImpl(types.TypeDecorator): | |
| impl = types.DateTime | |
| def process_bind_param(self, value, dialect): | |
| """Value that will be persisted in the database.""" | |
| if value is not None: | |
| if not isAware(value): | |
| value = value.replace(tzinfo=localtz) | |
| return makeNaive(value.astimezone(tz)) | |
| def process_result_value(self, value, dialect): | |
| """Value that is being retrieved from the database.""" | |
| if value is not None: | |
| return value.replace(tzinfo=tz) | |
| def compare_values(self, x, y): | |
| x, y = [ makeAware(val or datetime.datetime.min) for val in (x, y) ] | |
| return x < y | |
| return AwareDateTimeImpl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment