【问题标题】:How to insert timestamp into GQL DateTimeProperty()?如何将时间戳插入 GQL DateTimeProperty()?
【发布时间】:2013-03-13 20:04:29
【问题描述】:

我的 cron 工作的目标是将带有时间戳的推文保存到 Google App Engine 的数据存储中。我无法弄清楚如何以时间戳形式保存数据(当前保存为字符串)。理想情况下,我想将其保存为 DateTimeProperty,以便更轻松地对条目进行排序。我正在努力解决两个特别的问题:

  1. 正确使用time.mktime(),和
  2. 将正确的格式化值放入 GQL

该字段在 json 中的格式如下:

s = "Wed, 20 Mar 2013 05:39:25 +0000"

我尝试使用datetime 模块来解析这个字符串:

timestr = datetime.datetime.strptime(s, "%a, %b %Y %d %H:%M:%S +0000")
when = datetime.fromtimestamp(time.mktime(timestr))

总结一下,这是我的 cron.py 文件的 sn-p:

result = simplejson.load(urllib.urlopen(twitterurl))
for item in result['results']:

g = ""
try:
    g = simplejson.dumps(item['geo']['coordinates'])
except:
    pass

timestr = datetime.datetime.strptime(str(item['created_at']), "%a, %b %Y %d %H:%M:%S +0000")
when = datetime.fromtimestamp(time.mktime(timestr))

tStore = TweetsFromJSON(user_id=str(item['from_user_id']),
                        user=item['from_user'], 
                        tweet=unicodedata.normalize('NFKD', item['text']).encode('ascii', 'ignore'),
                        timestamp=when,
                        iso=item['iso_language_code'], 
                        geo=g
                        )

数据存储的模型是:

class TweetsFromJSON(db.Model):
    user = db.TextProperty()
    user_id = db.TextProperty()
    tweet = db.TextProperty()
    timestamp = db.DateTimeProperty()
    iso = db.StringProperty()
    geo = db.StringProperty()

【问题讨论】:

    标签: python google-app-engine datetime python-2.7 gql


    【解决方案1】:

    您应该使用以下格式来扫描带有datetime.strptime的时间字符串:

    "%a, %d %b %Y %H:%M:%S %z"
    

    这在 Python 3 中可以正常工作:

    Python 3.3.0 (default, Mar 22 2013, 20:14:41) 
    [GCC 4.2.1 Compatible FreeBSD Clang 3.1 ((branches/release_31 156863))] on freebsd9
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from datetime import datetime
    >>> s = 'Wed, 20 Mar 2013 05:39:25 +0000'
    >>> datetime.strptime(s, "%a, %d %b %Y %H:%M:%S %z")
    datetime.datetime(2013, 3, 20, 5, 39, 25, tzinfo=datetime.timezone.utc)
    

    请注意,这会返回一个datetime 对象,因此无需进一步操作。

    不幸的是,这在 Python 2 中不起作用;

    Python 2.7.3 (default, Jan 17 2013, 21:23:30) 
    [GCC 4.2.1 Compatible FreeBSD Clang 3.0 (branches/release_30 142614)] on freebsd9
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from datetime import datetime
    >>> s = 'Wed, 20 Mar 2013 05:39:25 +0000'
    >>> datetime.strptime(s, "%a, %d %b %Y %H:%M:%S %z")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/_strptime.py", line 317, in _strptime
        (bad_directive, format))
    ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'
    

    这似乎是 Python 2.7 中的一个错误。 documentation 提到了%z,但/usr/local/lib/python2.7/_strptime.py 中的代码不包含与之匹配的正确正则表达式。

    作为 Python 2 的解决方法,您可以尝试以下方法:

    >>> datetime.strptime(s[:-6], "%a, %d %b %Y %H:%M:%S")
    datetime.datetime(2013, 3, 20, 5, 39, 25)
    

    这只是切断了最后 6 个字符。这只有在时区偏移量有符号和四位数字时才能正常工作。另一种选择是使用splitjoin

    >>> datetime.strptime(' '.join(s.split()[:-1]), "%a, %d %b %Y %H:%M:%S")
    datetime.datetime(2013, 3, 20, 5, 39, 25)
    

    据我了解,您必须自己扫描时区信息,创建自定义 tzinfo 子类(使用链接文档中的 FixedOffset 类示例)并使用 datetime.replace() 将其放入 datetime对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      相关资源
      最近更新 更多