【问题标题】:SQLAlchemy filter by combined date and time with timezoneSQLAlchemy 按组合日期和时间与时区过滤
【发布时间】:2017-03-03 12:06:55
【问题描述】:

更新

@datetime_as_timestamp.expression
def datetime_as_timestamp(cls):
    return db.func.timestamp(cls.date, cls.time)

@datetime_as_timestamp.expression
def datetime_as_timestamp(cls):
    return cls.date + cls.time

原创

我的模型中有日期和时间。在另一张表中有他们的时区,但为了简单起见,我将手动进行。我想按日期+时间+时区过滤。

class Foo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.Date)
    time = db.Column(db.Time)

    @hybrid_property
    def datetime_as_timestamp(self):
        return time.mktime(
            datetime.datetime.combine(self.date, self.time).timetuple()
        )

    @datetime_as_timestamp.expression
    def datetime_as_timestamp(cls):
        return db.func.timestamp(cls.date, cls.time)

但是当我执行过滤查询时

In [1]: Foo.query.filter(func.timezone('Australia/Brisbane', Foo.datetime_as_timestamp) <= func.timezone('UTC', func.current_timestamp())).one()

我收到一个错误

psycopg2.ProgrammingError) syntax error at or near "foo"
LINE 3: WHERE timezone('Australia/Brisbane', timestamp(foo.da...
                                                  ^
 [SQL: 'SELECT foo.id AS checkin_flight_id, foo.date AS checkin_flight_date, foo.time AS checkin_flight_time \nFROM foo \nWHERE timezone(%(timezone_1)s, timestamp(foo.date, foo.time)) <= timezone(%(timezone_2)s, CURRENT_TIMESTAMP)'] [parameters: {'timezone_2': 'UTC', 'timezone_1': 'Australia/Brisbane'}]

我错过了什么,我的错误在哪里?是否可以通过其他方式解决我的问题?

【问题讨论】:

    标签: python-3.x datetime filter sqlalchemy timezone


    【解决方案1】:

    我发现这个Q&A 很有帮助。我变了

    @datetime_as_timestamp.expression
    def datetime_as_timestamp(cls):
        return db.func.timestamp(cls.date, cls.time)
    

    @datetime_as_timestamp.expression
    def datetime_as_timestamp(cls):
        return cls.date + cls.time
    

    一切正常

    【讨论】:

      猜你喜欢
      • 2017-08-04
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2015-03-06
      • 2013-10-20
      相关资源
      最近更新 更多