如何使用Tweepy获取推文的年龄?

时间:2014-04-29 05:51:08

标签: python python-2.7 twitter tweepy

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

1 个答案:

答案 0 :(得分:0)

实际上这很容易。您收集的每条推文都标有BUNCH数据,包括发布日期。您可以使用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,轻松转换为分钟。