Created
April 22, 2013 20:42
-
-
Save drawks/5438362 to your computer and use it in GitHub Desktop.
Example of type coercion for sqlalchemy.
This file contains 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
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