Created
June 24, 2018 22:03
-
-
Save inklesspen/2378852985b49907e09374031f02f660 to your computer and use it in GitHub Desktop.
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
from sqlalchemy.types import DATETIME # optionally import this from your specific dialect | |
from sqlalchemy.types import TypeDecorator | |
import datetime | |
import pytz | |
class TzDateTime(TypeDecorator): | |
impl = DATETIME | |
tz = pytz.utc | |
def process_bind_param(self, value, dialect): | |
if value is None: | |
return None | |
if not isinstance(value, datetime.datetime): | |
raise TypeError("%r is not an instance of %r" % (value, datetime.datetime)) | |
if value.tzinfo is None: | |
raise TypeError("%r is a naive datetime" % value) | |
localized = self.tz.normalize(value.astimezone(self.tz)) | |
return localized.replace(tzinfo=None) | |
def process_result_value(self, value, dialect): | |
if value is None: | |
return None | |
if not isinstance(value, datetime.datetime): | |
raise TypeError("%r is not an instance of %r" % (value, datetime.datetime)) | |
if value.tzinfo is not None: | |
raise TypeError("%r is not a naive datetime" % value) | |
return self.tz.localize(value) | |
@classmethod | |
def now(self): | |
return datetime.datetime.now(self.tz) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment