Going from twitter date to Python datetime date

Javaaaa picture Javaaaa · Oct 9, 2011 · Viewed 28.3k times · Source

I am receiving twitter messages that are sent at a certain date in the following format from twitter:

Tue Mar 29 08:11:25 +0000 2011

I want to store these dates in 'timestamp with time zone' field in postgresql with djangos DateTimeField field. When I store that string however I get this error:

ValidationError: [u'Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.']

can I automatically transform the twitter datetype to a python datetime time (that does work elsewhere in my app for saving dates).

Answer

Chris Herring picture Chris Herring · Oct 10, 2011

Writing something like this should convert a twitter date to a timestamp.

import time

ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))

UPDATE

For Python 3, as per 2020, you can do it in this way:

from datetime import datetime

# dtime = tweet['created_at']
dtime = 'Fri Oct 09 10:01:41 +0000 2015'
new_datetime = datetime.strftime(datetime.strptime(dtime,'%a %b %d %H:%M:%S +0000 %Y'), '%Y-%m-%d %H:%M:%S')
print((new_datetime))