Defining a table with sqlalchemy with a mysql unix timestamp

前端 未结 2 1186
走了就别回头了
走了就别回头了 2021-01-13 14:56

Background, there are several ways to store dates in MySQ.

  1. As a string e.g. \"09/09/2009\".
  2. As integer using the function UNIX_TIMESTAMP() this is sup
2条回答
  •  情深已故
    2021-01-13 14:57

    So yeah, this approach works. And I ended up answering my own question :/, hope somebody finds this useful.

    import datetime, time
    from sqlalchemy.types import TypeDecorator, DateTime
    class IntegerDateTime(TypeDecorator):
        """a type that decorates DateTime, converts to unix time on
        the way in and to datetime.datetime objects on the way out."""
        impl = DateTime
        def process_bind_param(self, value, engine):
            """Assumes a datetime.datetime"""
            assert isinstance(value, datetime.datetime)
            return int(time.mktime(value.timetuple()))
        def process_result_value(self, value, engine):
            return datetime.datetime.fromtimestamp(float(value))
        def copy(self):
            return IntegerDateTime(timezone=self.timezone)
    

提交回复
热议问题