Skip to main content
 首页 » 编程设计

python之在 Google App Engine Datastore 中按日期过滤

2025年05月04日28dyllove98

我在尝试按日期过滤一组对象时遇到了一些问题。现在我可以得到所有的 用户的交易是这样的:

> t = Transaction.all().filter("client_email =", "some_email").filter("application_id =", "foo").fetch(100) 
> len(t) 
# => 4 

现在,如果我想设置一些日期过滤器:

> min = datetime.datetime(2009, 2, 3, 0, 0) 
> max = datetime.datetime(2009, 11, 4, 0, 0) 
 
> len(Transaction.gql("WHERE client_email =:1 AND date >:2 AND date <=:3 AND application_id =:4",  
                      "some_email", min, max, "foo").fetch(100)) 
# => 2 

我知道所有这些交易都有一个日期 < max && > min:

> map(lambda x: x.date, t) 
# => [datetime.datetime(2009, 10, 2, 22, 43, 51), datetime.datetime(2009, 10, 5, 2, 5, 24), datetime.datetime(2009, 10, 7, 16, 51, 5), datetime.datetime(2009, 10, 7, 16, 6, 53)] 

是的,所有这些交易都是在 2009 年 10 月进行的。我用 Python 过滤它们只是为了确认 这是对的:

> trans = filter(lambda x: x.date < max and x.date >= min, t) 
> len(trans) 
# => 4 

是的,它们都有正确的日期,但由于我查询中的某些内容,结果与 预期结果,知道查询中可能有什么问题吗?

请您参考如下方法:

您是否尝试过使查询日期信息符合 App Engine GQL syntax ?。例如语法:

DATETIME(year, month, day, hour, minute, second) 
DATETIME('YYYY-MM-DD HH:MM:SS') 
DATE(year, month, day) 
DATE('YYYY-MM-DD') 
TIME(hour, minute, second) 
TIME('HH:MM:SS') 

尝试运行以下 GQL:

"WHERE client_email =:1 AND date > DATE(:2) AND date <= DATE(:3) AND application_id =:4", "some_email", "2009-02-03", "2009-11-04", "foo"