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 dateutil.tz 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())

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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