【问题标题】:How can I get the age of a tweet using Tweepy?如何使用 Tweepy 获取推文的年龄?
【发布时间】:2014-05-03 15:08:32
【问题描述】:

我正在尝试使用 Tweepy 获取一个列表,以获取来自特定用户一周以上的推文列表,但我无法弄清楚如何获取推文的年龄。截至目前,我知道如何获取推文列表,但我在文档中找不到任何关于获取推文年龄的信息。 Tweepy 是否存在这样的事情,还是我应该只使用不同的库?如果是这样,我可以使用具有此功能的哪个库?谢谢!

【问题讨论】:

  • 您能发布您用来收集推文的代码吗?

标签: python python-2.7 twitter tweepy


【解决方案1】:

其实很简单。您收集的每条推文都标有一堆数据,包括发布日期。您可以使用Status.created_at 属性访问它们:

import tweepy, time, datetime

CONSUMER_KEY = '#'
CONSUMER_SECRET = '#'
ACCESS_TOKEN = '#'
ACCESS_TOKEN_SECRET = '#'
key = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
key.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(key)

results = api.search(q='tryptophan')

dates = []

for tweet in results:
    dates.append(tweet.created_at)

ages = []

for d in dates:
    # to compare against time.time(), we must use seconds since the epoch (1/1/1970)
    # time.time() returns the current time, in seconds, since 1/1/1970
    age = time.time() - (d - datetime.datetime(1970,1,1)).total_seconds()
    ages.append(age) # age in seconds

for i in range(0,len(ages)):
    print 'Tweeted:', str(dates[i]) + ', age in seconds:', ages[i]

结果:

Tweeted: 2014-05-03 05:39:40, age in seconds: 4564.01300001
Tweeted: 2014-05-03 04:45:47, age in seconds: 7797.01300001
Tweeted: 2014-05-03 04:21:40, age in seconds: 9244.01300001
Tweeted: 2014-05-03 03:56:01, age in seconds: 10783.013
Tweeted: 2014-05-03 01:24:53, age in seconds: 19851.013
Tweeted: 2014-05-03 00:44:49, age in seconds: 22255.013
Tweeted: 2014-05-03 00:31:50, age in seconds: 23034.013
Tweeted: 2014-05-02 22:23:15, age in seconds: 30749.013
Tweeted: 2014-05-02 22:00:12, age in seconds: 32132.013
Tweeted: 2014-05-02 21:22:18, age in seconds: 34406.013
Tweeted: 2014-05-02 20:54:45, age in seconds: 36059.013
Tweeted: 2014-05-02 20:33:59, age in seconds: 37305.013
Tweeted: 2014-05-02 20:31:45, age in seconds: 37439.013
Tweeted: 2014-05-02 15:16:43, age in seconds: 56341.013
Tweeted: 2014-05-02 15:05:03, age in seconds: 57041.013

自纪元以来的秒数有点时髦,您可以阅读更多here。这里的年龄以秒为单位,但您可以通过除以 60 轻松转换为分钟,再除以 60 转换为小时,再除以 360 转换为天。

【讨论】:

  • 作者询问如何在一周后检索推文。即使他可以获取 created_at 数据,该 api 仍然不会为您提供超过一周的推文。
猜你喜欢
  • 1970-01-01
  • 2019-04-09
  • 2020-09-02
  • 1970-01-01
  • 2020-09-07
  • 2016-01-07
  • 2019-05-06
  • 2019-02-25
  • 2016-08-11
相关资源
最近更新 更多