Use custom datetime type for all datetime column with autoload

30 views
Skip to first unread message

Rit Li

unread,
Jul 18, 2013, 1:36:25 AM7/18/13
to sqlal...@googlegroups.com
How can I make all datetime columns to use my UTCDateTime type by default?

from sqlalchemy import types
from pytz import utc

Base = declarative_base()

class UTCDateTime(types.TypeDecorator):

    impl = types.DateTime

    def process_bind_param(self, value, engine):
        if value is not None:
            return value.astimezone(utc)

    def process_result_value(self, value, engine):
        if value is not None:
            return value.replace(tzinfo=utc)


class Game(Base):
    __table__ = Table('games', metadata, autoload=True)

Michael Bayer

unread,
Jul 18, 2013, 10:02:05 AM7/18/13
to sqlal...@googlegroups.com
the most straightforward way is to use an event:

from sqlalchemy.schema import Table
from sqlalchemy import event

@event.listens_for(Table, "column_reflect")
def set_utc_date(inspector, table, column_info):
    if isinstance(column_info['type'], DateTime):
        column_info['type'] = UTCDateTime()




--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Rit Li

unread,
Jul 18, 2013, 2:04:03 PM7/18/13
to sqlal...@googlegroups.com
That works! Thank you, Michael.


--
You received this message because you are subscribed to a topic in the Google Groups "sqlalchemy" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/sqlalchemy/aurk5dXu2Rc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to sqlalchemy+...@googlegroups.com.

To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
Rit
213-254-5748
Reply all
Reply to author
Forward
0 new messages