18

I have a model with a date column defined as :

created_on = db.Column(db.DateTime, default=db.func.now(), nullable=False)

The dates comme out with tz_info=None, which is correct, since the dates are stored without timezone info.

If I print the date :

print(my_object.created_on.isoformat())

I get this format

2014-04-26T17:46:27.353936

I would like to have a UTC timezone indicator, such as :

2014-04-26T17:46:27.353936Z

Is there a way to define this behavior in the schema config ?

SQLAlchemy has, timezone=Boolean

sqlalchemy.types.DateTime(timezone=False)

since I want the storage to be without timezone.

2 Answers 2

19

You want a custom data type, described here: http://docs.sqlalchemy.org/en/rel_0_9/core/types.html#custom-types

Specifically, something like this:

import pytz  # from PyPI

class AwareDateTime(db.TypeDecorator):
    '''Results returned as aware datetimes, not naive ones.
    '''

    impl = db.DateTime

    def process_result_value(self, value, dialect):
        return value.replace(tzinfo=pytz.utc)

Then just make the column like this:

created_on = db.Column(AwareDateTime, default=db.func.now(), nullable=False)
Sign up to request clarification or add additional context in comments.

Comments

11

I would recommend to use Arrow type.

from datetime import datetime
from sqlalchemy_utils import ArrowType
import arrow


class Article(Base):
    __tablename__ = 'article'
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.Unicode(255))
    created_at = sa.Column(ArrowType)



article = Article(created_at=arrow.utcnow())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.