SQLAlchemy DateTime timezone

前端 未结 4 1115
情话喂你
情话喂你 2021-01-31 07:54

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

4条回答
  •  半阙折子戏
    2021-01-31 08:15

    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)
    

提交回复
热议问题