abhidoeslinux
abhidoeslinux

Reputation: 151

How do I convert python time.gmtime() to MongoDB Date

I need to convert the time returned by gmtime() to a readable string. As a mistake, I populated huge data in mongo and stored date as a string. After the discussion in my previous question I am just doing a regex match to get the relevant data from mongo. The problem now is to convert gmtime which is say:

time.struct_time(tm_year=2015, tm_mon=10, tm_mday=9, tm_hour=9, tm_min=49, tm_sec=31, tm_wday=4, tm_yday=282, tm_isdst=0)

to this:

Tue 27 Jan 2015

This is the string format that is stored in mongo

{
    "startTime" : "Sun 25 Jan 2015 07:14:26 GMT",
    "endTime" : "",
    "jobStatus" : "JOBCANCELLED",
    "uiState" : "HISTORY",
    "priority" : "SILVER"
}

Dumb way to make Mongo query work:

db.getCollection('jobsCollection').find({"startTime":{$regex: "Tue 27 Jan 2015.*"}})

I need to convert the gmtime to the regex attribute shown in the mongo query

Is there any way I can achieve this?

Upvotes: 0

Views: 242

Answers (3)

Blakes Seven
Blakes Seven

Reputation: 50436

You asked the wrong question and hence got the wrong answers. What you really want to do is convert your current string into a BSON Date.

Yep just do it in the shell as it's a lot more simple to write that way, and it's a "one off" process, so why write a longer program?:

var bulk = db.jobsCollection.initializeOrderedBulkOp(),
    count = 0;

db.jobsCollection.find({ "startTime": { "$type": 2 } }).forEach(function(doc) {
    bulk.find({ "_id": doc._id }).updateOne({
        "$set": { "startTime": new Date(doc.startTime) }
    });
    count++;

    if ( count % 1000 == 0 ) {
        bulk.execute();
        bulk = db.jobsCollection.initializeOrderedBukOp();
    }
});

if ( count % 1000 != 0 )
    bulk.execute();

And that will convert each string into a BSON Date type in the most efficient and safe way possible.

Upvotes: 0

Anurag Verma
Anurag Verma

Reputation: 495

import time
print time.gmtime(123456)
print time.strftime("%A %d-%b-%Y", time.gmtime(time.time()))
>>>Friday 09-Oct-2015

Upvotes: 1

Marius M
Marius M

Reputation: 496

strftime function should do the trick for you.

Upvotes: 0

Related Questions