Inserting field with date Datetype is working with mongoimport and not with insert_one in pymongo

Json file example

[
      {

            "build_info": {

                  "os_version": "Ubuntu-20.04",

                  "scheduler": "bng-dev-icesch",

                  "start_time": {

                        "$date": "2022-12-22T12:18:06.844+0530"

                  },

                  "stop_time": {

                        "$date": "2022-12-22T12:18:48.944+0530"

                  },

                  "user": "rhadagali",

                  "build_status": "Passed"

   

            }

      }
]

using mongoimport (inside DB)

 start_time: ISODate("2022-12-22T06:48:06.844Z"),
 stop_time: ISODate("2022-12-22T06:48:48.944Z"),

using insert_one from pymongo

start_time: { '$date': '2022-12-22T12:18:06.844+0530' },
stop_time: { '$date': '2022-12-22T12:18:48.944+0530' },

Should i change pymongos insert_one to make it to take it as date datetype ?

Hi @Stuart_S ,

you can use the datetime module in Python to create datetime objects, and then pass those directly to insert_one as the values for the start_time and stop_time fields. pymongo will automatically convert the datetime objects to BSON date types when inserting them into the collection.

For example:

import datetime

start_time = datetime.datetime(2022, 12, 22, 6, 48, 6, 844000)
stop_time = datetime.datetime(2022, 12, 22, 6, 48, 48, 944000)

document = {
    'start_time': start_time,
    'stop_time': stop_time
}

result = collection.insert_one(document)

Will that work as expected.

Thanks

1 Like

Thanks for the reply @Pavel_Duchovny , Should i change my json format ?

I thought you wanted paymongo to produce:

tart_time: ISODate("2022-12-22T06:48:06.844Z"),
 stop_time: ISODate("2022-12-22T06:48:48.944Z"),

This is a natural way of storing it in MongoDB.

If so you need to adjust the python code as suggested.

Pavel

Thanks @Pavel_Duchovny , i was able to import those fields as date datatype in DB

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.