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
Twitter API V2 sends date strings that look like this:
2020-12-15T20:17:10.000Z
This worked, to convert from string to datetime:
datetime.datetime.strptime(THE_STRING,"%Y-%m-%dT%H:%M:%S.%fZ")
The end looks like a timezone, but it's milliseconds, hence the %f. The final character, "Z" is a timezone code that means UTC, as explained, here.
The initial problem I was having was converting from the datetime that the twitter api gives to String.
The following works which addresses different comments people seem to have for above solutions which are a little unclear as to whether the starting date is already in string format or not. This works for Python 2.7
With a tweet from the API, tweet.created_at gives the date in datetime format. At the top of your file, add from datetime import datetime
then use the following to get the corresponding string.
datetime.strftime(tweet.created_at,'%a %b %d %H:%M:%S %z %Y').
You can then use this string as described in other comments to manipulate it.
you can convert the date using datetime.strptime()
, or time.strptime()
. however, those two functions cannot parse the timezone offset (see this bug).
so, the only solution i see is to split the date yourself, remove the timezone offset, feed the rest to strptime()
, and process the offset manually...
have a look at this question, where you will find some hints on how to parse the offset yourself.
To get datetime with timezone you can simple use datetime.strptime as follow:
from datetime import datetime
s = 'Wed Jun 05 05:34:02 +0000 2019'
created_at = datetime.strptime(s, '%a %b %d %H:%M:%S %z %Y')
print(created_at)
#2019-06-05 05:34:02+00:00