Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy How to load dates with timezone=UTC (dates stored without timezone)

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.

like image 590
Max L. Avatar asked Apr 26 '14 20:04

Max L.


People also ask

How to get rid of timezone in datetime?

The solution is to convert your datetime. datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself.

Is Python datetime in UTC?

Practical Data Science using PythonYou can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.

How do you add time zones in Python?

You can also use the pytz module to create timezone-aware objects. For this, we will store the current date and time in a new variable using the datetime. now() function of datetime module and then we will add the timezone using timezone function of pytz module.


1 Answers

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)
like image 162
Vanessa Phipps Avatar answered Oct 11 '22 20:10

Vanessa Phipps