Convert datetime to unix timestamp in SQLAlchemy model before executing query?

前端 未结 1 1562
甜味超标
甜味超标 2021-01-12 16:59

I am using SQLAlchemy to work with a remote database that uses a strange timestamp format--it stores timestamps as double-precision milliseconds since epoch. I\'d like to wo

1条回答
  •  执念已碎
    2021-01-12 17:29

    You have to use a custom type, which isn't as scary as it sounds.

    from sqlalchemy.types import TypeDecorator
    
    
    class DoubleTimestamp(TypeDecorator):
        impl = DOUBLE
    
        def __init__(self):
            TypeDecorator.__init__(self, as_decimal=False)
    
        def process_bind_param(self, value, dialect):
            return value.replace(tzinfo=datetime.timezone.utc).timestamp() * 1000
    
        def process_result_value(self, value, dialect):
            return datetime.datetime.utcfromtimestamp(value / 1000)
    

    Then Table becomes:

    class Table(Base):
        __tablename__ = "table"
    
        id = Column(Integer, primary_key=True)
        timestamp = Column(DoubleTimestamp)
    

    And then everything you mention works. You insert, select and compare with datetimes but it's stored as a DOUBLE.

    Here I've used different logic for converting between timestamps since strftime('%s') isn't the correct solution. It's a different question which has been answered correctly here. Oh and I noticed you said microseconds but only convert to milliseconds in the code you posted, unless it was a slip of the tongue

    0 讨论(0)
提交回复
热议问题