【问题标题】:GQL Query (python) to retrieve data using timestampGQL 查询(python)使用时间戳检索数据
【发布时间】:2014-02-19 13:33:39
【问题描述】:

我在 Google Datastore 中有一个表,它在 n 列中保存 n 个值,其中一个是 timestamp

timestamp 属性在表类 (Java) 中定义如下:

@Persistent
private Date timestamp;

表格是这样的:

    id    |    value    |            timestamp    
----------------------------------------------------------
     1    |    ABC      |    2014-02-02 21:07:40.822000   
     2    |    CDE      |    2014-02-02 22:07:40.000000   
     3    |    EFG      |       
     4    |    GHI      |    2014-02-02 21:07:40.822000   
     5    |    IJK      |       
     6    |    KLM      |    2014-01-02 21:07:40.822000   

timestamp 列是后来添加到表中的,因此某些行没有对应的timestamp 值。

我正在尝试使用 Python Google App Engine 构建一个 API,该 API 将具有时间戳 >= 的总行数返回到某个值。

例如:

-- This is just an example
SELECT * FROM myTable WHERE timestamp >= '2014-02-02 21:07:40.822000'

我已经在 python 中创建了这个类:

import sys
...
import webapp2

from google.appengine.ext import db

class myTable(db.Model):
    value = db.StringProperty()
    timestamp = datetime.datetime

class countHandler(webapp2.RequestHandler):
    def get(self, tablename, timestamp):

        table = db.GqlQuery("SELECT __key__ FROM " + tablename + " WHERE timestamp >= :1",  timestamp )
        recordsCount = 0

        for p in table:
            recordsCount += 1

         self.response.out.write("Records count for table " + tablename + ": " + str(recordsCount))

app = webapp2.WSGIApplication([
    ('/count/(.*)/(.*)', countHandler)
], debug=True)

我已经成功部署它并且可以调用它,但由于某种原因我不明白它总是在说

Records count for table myTable: 0

我正在为时间戳的数据类型而苦苦挣扎。我认为问题就在那里。有什么想法吗?应该声明哪种类型?

谢谢!

【问题讨论】:

  • 您确定时间戳不是字符串吗?据我所知,它必须是日期时间。
  • @JimmyKane 我在 Java 类中将其定义为 Date,所以它应该是日期。我会尝试一下,python 方面,如果是这样的话,使用 timestamp = db.StringProperty()你的意思是
  • 我认为您需要有日期时间格式的时间戳。只需将其转换为日期时间并使用该对象进行查询。通知它是否有效。我有一些时间在我的查询中使用它,而 atm 我没有方便测试。
  • @JimmyKane 很抱歉很无聊,但你的意思是 python 或 java 端? (也许在 python 中有一些 datetimedatetime.datetime 不同?)
  • @JimmyKane 你的提示解决了我的问题,谢谢。如果您回复原始问题,我将接受您的回答!再次感谢!

标签: google-app-engine python-2.7 google-cloud-datastore


【解决方案1】:

您的问题(如 cmets 中所讨论的)似乎是您正在将字符串(可能)传递给 GqlQuery 参数。

为了通过datetime 过滤您的查询,您需要将datetime 对象传递给查询参数。为此,请查看 here 了解如何转换它。

小例子:

# not sure how your timestamps are formatted but supposing they are strings
# of eg 2014-02-02 21:07:40.822000
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f" )

table = db.GqlQuery("SELECT __key__ FROM " + tablename + " WHERE timestamp >= :1",  timestamp)

【讨论】:

  • 其实我用了另一个例子:tmstmp = dateutil.parser.parse(timestamp)。请注意,这样,我需要下载并导入 dateutil 库。
  • @BeNdErR 当然也可以。我对 datetime 模块比较熟悉。很高兴它解决了它。
  • 您的解决方案可能会为我节省新库的导入 :)
猜你喜欢
  • 2013-05-06
  • 2016-03-09
  • 1970-01-01
  • 2015-02-09
  • 2011-04-20
  • 1970-01-01
  • 2022-10-31
  • 2016-05-04
  • 1970-01-01
相关资源
最近更新 更多