Search code examples
pythontwittertimezonepython-twitter

Using python-twitter library, how to set timezone?


I'm trying to list out tweets with their time-stamps. I have this...

#!/usr/bin/python
import twitter
api = twitter.Api()
statuses = api.GetUserTimeline('ttytter')
for s in statuses:
  print s.created_at + " " + s.text

Which prints out...

Sat Oct 20 04:56:47 +0000 2012 @uriel1998 W/r/t DMs, they appear just fine in 2.0.4 and 2.1 beta here, near as I can tell.

Which is pretty much what I'm after, but for the time, which seems to be in the wrong timezone. https://twitter.com/ttytter/status/259518502069760000

Is there a way I can change this within the python-twitter library? I was looking at GetTimeZone() and SetTimeZone(), but I haven't been able to figure out how they work.

Also looking at how to shift a datetime object by 12 hours in python but not sure if I need to go there.

Thanks for any help!


Solution

  • python-twitter returns the status timestamps as a string and as the number of seconds since the epoch. The latter is the simplest to convert to a timezone-aware datetime instance (see this answer).

    Unfortunately the user's time_zone attribute is not in the standard tz database format used by pytz, so it is necessary to use the utc_offset user attribute instead (we still use the time_zone attribute to name the tzinfo created with with the UTC offset). The python-dateutil package provides a convenience type tzoffset that allows the creation of tzinfo instances from UTC offsets, which we can then use to convert the datetime from UTC to the local time zone:

    import pytz
    import twitter
    
    from datetime import  datetime
    from dateutil.tz import tzoffset
    
    USERNAME = 'ttytter'
    
    api = twitter.Api()
    
    # get a 'tzinfo' instance with the UTC offset for the user's local time
    user = api.GetUser(USERNAME)
    localtime_tz = tzoffset(user.time_zone, user.utc_offset)
    
    statuses = api.GetUserTimeline(USERNAME)
    for s in statuses[:1]:
        # get UTC timestamp from seconds since epoch
        utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
        print('utc: {}'.format(utc_dt))
        # convert to local time in the user's timezone
        localtime_dt = utc_dt.astimezone(localtime_tz)
        print('localtime [{}]: {}'.format(localtime_dt.tzname(), localtime_dt))
    

    which gives the output for the first status:

    utc: 2012-10-20 04:56:47+00:00
    localtime [Pacific Time (US & Canada)]: 2012-10-19 20:56:47-08:00