title: How to convert JSON inserted created_at field in MongoDB to datetime objects in Python
body: <p>I have been mining data from twitter for several weeks and without really thinking I inserted it directly into MongoDB directly as the JSON structure.</p>
  
  <p>This appears to have caused a problem with the "created_at" field being in String format rather than datetime. This basically makes my indexes useless if I want to withdraw tweets from a collection between certain dates.</p>
  
  <p>I am using python tweepy package and have been inserting the json tweets into mongodb like so:</p>
  
  <pre><code>    collection.insert(json.loads(data))
  </code></pre>
  
  <p>where data is like for example:</p>
  
  <pre><code>    {"created_at":"Tue Dec 03 23:07:53 +0000 2013","id":408009726509596672,"id_str":"408009726509596672","text":"this is some text"}
  </code></pre>
  
  <p>How can I programatically convert all of the String "created_at" dates into datetime objects within the collections?</p>
  
  <p>What would be the best way to "find" the tweets and iterate through them from the database? </p>
  
  <p>I have been trying something like this:</p>
  
  <pre><code>import pymongo, datetime
  
  from pymongo import MongoClient
  
  client = MongoClient()
  
  #access database
  db = client.tweets
  
  #access collection
  collection = db.collection_name
  
  
  tweets = collection.find({}) #just get all of the tweets in the collection.
  
  for tweet in tweets:
      print tweet #how do I update the created_at field for each tweet in the collection  here?
  </code></pre>
  
  <p><strong>EDIT:</strong>
  I ended up using a hybrid of both Jose and Xcorat's answers.</p>
  
  <p>For those that wish to do this purely in Python (continuing on from my code above) this is what I did:</p>
  
  <pre><code>for tweet in tweets:
      thedate = tweet[u'created_at'] #in my case I was storing the date as unicode not datetime.
      if(type( thedate ) == unicode):
          proper_date = datetime.datetime.strptime(thedate,'%a %b %d %H:%M:%S +0000 %Y')
          pointer = tweet[u'_id']
          collection.update({'_id': pointer}, {'$set': {'created_at': proper_date}})
          print('updated created_at from unicode to datetime\n')
      else:
          print('skipping as is already datetime...\n')
  </code></pre>