Python Recipe – Return Sqlalchemy date in isoformat

when decoding the data into a list, for time columns using the isoformat() method as shown in the above image.

class Message(Base):
    __tablename__ = 'message'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    time_created = Column(DateTime(timezone=True), server_default=func.now())
    time_updated = Column(DateTime(timezone=True), server_default=func.now())

    def to_json(self):
        # get columns data
        data = {}
        columns = list(self.__table__.columns)
        for column in columns:
            if column.name == 'time_created':
                data[column.name] = self.time_created.isoformat()
            elif column.name == 'time_updated':
                data[column.name] = self.time_updated.isoformat()
            else:
                data[column.name] = self.__dict__[column.name]
        return data

Leave a Reply

Your email address will not be published.