1

I am using pymongo

I have a mongo db in which all documents have a "timestamp" : "25-OCT-2011"

So a string is stored in the key timestamp in all documents.

I want to apply a python function as mentioned below on these string dates and convert them into a datetime object. What's the best way to do this in mongodb?

import datetime
def make_date(str_date):  
    return datetime.datetime.strptime(str_date, "%d-%b-%Y")
4

1 に答える 1

1

あなたのニーズに合うように:

import bson    

for document in list(database.collection.find({ })):
   converted_date = make_date(document['timestamp'])
   database.collection.update(
         { "_id": bson.objectid.ObjectId(document['_id']) },
         { "converted": converted_date }
   )

ObjectIdをクエリとして使用して、取得したばかりのドキュメントを確実に更新します。タイムスタンプの衝突が望ましくない結果につながるかどうかわからないため、これを行います。

于 2012-04-15T11:08:35.327 に答える