Reputation: 670
I am trying to parse string into python datetime object and this is the code:
created = datetime.strptime(r.json()[x]["created_at"], "%a %b %d %H:%M:%S +0000 %Y")
The error I get is:
ValueError: time data '"Wed Jan 16 22:08:18 +0000 2013"' does not match format '%a %b %d %H:%M:%S +0000 %Y'
It should be correct, obviously I am doing something wrong. As a note, the r.json returns the text in unicode, but I tried it with a str() conversion as well.
The full program:
import requests
from datetime import datetime
from simplejson import dumps
url = 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name='
username = 'gtklondike'
count = '5'
url += username + "&count=" + count
r = requests.get(url)
x = 0
while x < count:
print "<div id='tw-body'>" + r.json()[x]["text"] + "</div>"
created = datetime.strptime(dumps(r.json()[x]["created_at"]), "%a %b %d %H:%M:%S +0000 %Y")
print "<div id='tw-date'>Date: " + r.json()[x]["created_at"] + "</div><br />\n" # TMP --> until I get datetime working... but at least it shows you the date
x = x + 1
Upvotes: 0
Views: 1385
Reputation: 21018
I would use the parse function provided by Delorean for future dealings with strptime e.g
>>> from delorean import parse
>>> parse("2011/01/01 00:00:00 -0700")
Delorean(datetime=2011-01-01 07:00:00+00:00, timezone=UTC)
It accepts a wide range of string input as well as take into account different timezones and provides easy mechanisms for shifting, to retrieve the required datetime object simple .datetime
on the delorean object.
Upvotes: 0
Reputation: 670
I found the issue! @wrgrs solution worked, but actually it is from the dumps() being around it, created an extra set of quotes. (It was his solution that triggered my idea)
created = datetime.strptime(r.json()[x]["created_at"], "%a %b %d %H:%M:%S +0000 %Y")
works just fine!
Upvotes: 2
Reputation: 2569
It looks to me like there's an extra set of quotes in your string - one ' denoting that it's a string, and one " inside the string.
Try:
created = datetime.strptime((r.json()[x]["created_at"]).strip('"'), "%a %b %d %H:%M:%S +0000 %Y")
strip('"')
removes the "
s from the string.
Upvotes: 3