Quick Guide To Using python-twitter

September 23, 2014

Twitter doesn’t have an official Python client for it’s REST API (which requires authentication for every query) but there are plenty of third party options. One of them is python-twitter, which is implements full API but lacks a decent documentation.

Here’s a full and working code on how to get a list of public tweets for a given screen name and an example of how to convert tweet dates from strings to datetime objects:

import twitter

# You'll find these from https://apps.twitter.com/
access_token_key = ''      # Twitter API key
access_token_secret = ''   # Twitter API secret
consumer_secret = ''       # Twitter Access token
consumer_key = ''          # Twitter Access token secret

# this functions needs 4 parameters or it will raise following exception:
# AttributeError: 'Api' object has no attribute '_Api__auth'
api = twitter.Api(

# this follows the REST API reference: https://dev.twitter.com/rest/public
timeline = api.GetUserTimeline(screen_name='djUninen', exclude_replies=True)

for tweet in timeline:
    print tweet.text

# finally, tweet.created_at returns a string, not a timestamp
# to convert the string into a datetime object, do this:
from datetime import datetime
tweet_timestamp = datetime.strptime(tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y")

One last exotic error to be aware of is an exception which says “Timestamp out of bounds”. It means that the environment clock is too far away from the actual time. For example if you’re running a local virtual machine which messes up its clock when the host goes to sleep, you might see this. (Note to self: how about finding a permanent fix for the god damn clock.)

Tagged with , , ,
Proudly Powered by Django
Unessa.net © 2000-2017 Ville Säävuori. All lefts reversed.