Skip to content

Instantly share code, notes, and snippets.

@inklesspen
Created June 24, 2018 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inklesspen/2378852985b49907e09374031f02f660 to your computer and use it in GitHub Desktop.
Save inklesspen/2378852985b49907e09374031f02f660 to your computer and use it in GitHub Desktop.
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