1

我的 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 文件的片段:

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()
4

1 回答 1

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 中的一个错误。文档中提到了 ,但其中%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 个字符。这只有在时区偏移量有符号和四位数字时才能正常工作。另一种选择是使用splitand join

>>> 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对象中。

于 2013-03-24T09:39:38.853 回答