Skip to content

Instantly share code, notes, and snippets.

@drawks
Created April 22, 2013 20:42
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 drawks/5438362 to your computer and use it in GitHub Desktop.
Save drawks/5438362 to your computer and use it in GitHub Desktop.
Example of type coercion for sqlalchemy.
class CoerceDateTime(TypeDecorator):
"""Extend DateTime to also coerce iso formatted datetime strings and epoch
ints in addition to native python datetimes"""
impl = DateTime
def process_bind_param(self, value, dialect):
if isinstance(value, str):
try:
value = iso8601.parse_date(value)
except:
pass
if isinstance(value, int):
try:
value = datetime.datetime.fromtimestamp(value)
except:
pass
return value
postgres.ischema_names['timestamp'] = CoerceDateTime
postgres.ischema_names['timestamp with time zone'] = CoerceDateTime
postgres.ischema_names['timestamp without time zone'] = CoerceDateTime
postgres.ischema_names['timestamp'] = CoerceDateTime
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment