Yasin Aktimur
Yasin Aktimur

Reputation: 459

Twitter created_at convert epoch time in python

I have this date from Twitter:

created_at = "Wed Aug 29 17:12:58 +0000 2012"

I want to convert it to a time using something like:

time.mktime(created_at)

But I get this error:

TypeError: argument must be 9-item sequence, not str

What am I doing wrong?

Upvotes: 2

Views: 5578

Answers (3)

Gestalti Lur
Gestalti Lur

Reputation: 31

I don't if it too late, use arrow package instead could fewer imports and a lot less code.

pip install arrow

Then:

>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y")
<Arrow [2012-08-29T17:00:58+00:00]>
>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y").timestamp
1346259658

Upvotes: 1

user764357
user764357

Reputation:

You need to convert the incoming string to a Python time tuple using strptime before you can do anything with it.

This code will take the input string, convert it to a tuple and then converts that to a Unix-epoch time float using time.mktime:

import time
created_at = "Wed Aug 29 17:12:58 +0000 2012"
print time.mktime(time.strptime(created_at,"%a %b %d %H:%M:%S +0000 %Y"))

Upvotes: 7

justhalf
justhalf

Reputation: 9107

Read the documentation of time.mktime

It requires struct_time, or you can alternatively represent it using a 9-tuple.

The required entries are:

  1. Year
  2. Month
  3. Date
  4. Hour
  5. Minute
  6. Second
  7. Day in week
  8. Day in year
  9. Daylight Savings Time

This is not the function you need, however. It seems that you want to use strptime instead.

According to the documentation:

Parse a string representing a time according to a format.
The return value is a struct_time as returned by gmtime() or localtime().

>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")   
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

So, you can do:

time.strptime(created_at)

Upvotes: 0

Related Questions