Going from twitter date to Python datetime date

前端 未结 10 1284
谎友^
谎友^ 2020-12-23 09:21

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

相关标签:
10条回答
  • 2020-12-23 10:11

    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.

    0 讨论(0)
  • 2020-12-23 10:15

    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.

    0 讨论(0)
  • 2020-12-23 10:17

    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.

    0 讨论(0)
  • 2020-12-23 10:18

    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
    
    0 讨论(0)
提交回复
热议问题