Make datetime naive for mysql in sqlalchemy

If you’re using mysql and are trying to store UTC datetime values, and elsewhere are sane enough to use datetime values that are timezone aware, here’s a little type for stripping out the timezone data on store and replacing it on load:

from sqlalchemy.types import TypeDecorator, DateTime
from import tzutc
from datetime import datetime

class UTCDateTime(TypeDecorator):

    impl = DateTime

    def process_bind_param(self, value, engine):
        if value is not None:
            return value.astimezone(tzutc()).replace(tzinfo=None)

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

One thought on “Make datetime naive for mysql in sqlalchemy

  1. Hi! I’m running into problems using a similar UTCDateTime custom type. Does anything immediately jump out to you looking at this?

    class Event(db.Model, CRUDMixin):
    timestamp = db.Column(UTCDateTime)

    an_event = Event.query.get(an_id)
    an_event_timestamp = an_event.timstamp

    # The following line does not work.
    # The filter does not output the correct events unless I switch to the normal db.DateType type
    events_before_an_event = BASEQUERY.filter(Event.timestamp <= an_event_timestamp).all()

    Looking at sqlaclhemy print outs it seems (not surprisingly) be doing the same SQL query when using DateType as UTCDateTime, which includes

    `event.timestamp <= %(timestamp_1)s` where timestamp_1 is datetime.datetime(2015, 10, 20, 23, 48, 15, 833153, tzinfo=)

    I assume looking up `event.timestamp` invokes `def process_result_value`.
    However, something is causing the incorrect events to match when I use UTCDateTime (in fact only events with timestamps greater than timestamp_1 are matching!)

    Really strange. Thanks for your attention

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s