SQLAlchemy\'s DateTime
type allows for a timezone=True
argument to save a non-naive datetime object to the database, and to return it as such. Is there
The following structure is recommended to store UTC date and time data in the database as well as to prevent data storage that does not have such location information.
import datetime
from sqlalchemy import DateTime
from sqlalchemy.types import TypeDecorator
class TZDateTime(TypeDecorator):
"""
A DateTime type which can only store tz-aware DateTimes.
"""
impl = DateTime(timezone=True)
def process_bind_param(self, value, dialect):
if isinstance(value, datetime.datetime) and value.tzinfo is None:
raise ValueError('{!r} must be TZ-aware'.format(value))
return value
def __repr__(self):
return 'TZDateTime()'
The values stored in the database should be defined as follows:
import datetime
import pytz
def tzware_datetime():
"""
Return a timezone aware datetime.
:return: Datetime
"""
return datetime.datetime.now(pytz.utc)