Michele
Michele

Reputation: 117

MongoDB / PyMongo / Python (Time): Getting the Datetime as String

I have a MongoDB database with the following structure within my documents:

> "_id": {
>       "mandant": "a4da7117-2763-48df-b3a3-d50a0f6006fe",
>       "ersteller": "9bc79ce4-c23a-4c24-a857-80f94a341d39",
>       "sender": "9bc79ce4-c23a-4c24-a857-80f94a341d39",
>       "vorgang": "c08382ed-143f-46f7-8382-ed143f26f7b8",
>       "nachricht": "6c9d3386-001f-4809-9d33-86001fd80990"
>     },
>     "_class": "de.codecraft.amt.storage.model.XAmtshilfe",
>     "created": {
>       "$date": "2018-10-02T09:20:05.060Z"
>     },

When I query with:

collection = db.find({}, {"_id": 0, "created": 1})

I got the following result:

{'created': datetime.datetime(2018, 11, 30, 13, 40, 4, 879000)}

How can I reach the pure datetime value, so I am able to parse it into other forms of time- types?

Thank you!

Upvotes: 7

Views: 12206

Answers (3)

Youngjae
Youngjae

Reputation: 25050

If someone wants to convert not only single datetime value but all values in a document, below json encoder could be helpful.

import json
import datetime

class MongoDbEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.astimezone().strftime("%Y-%m-%dT%H:%M:%S.%f%z")
        return json.JSONEncoder.default(self, obj)

# usage
json_document = json.dumps(result, cls=MongoDbEncoder)

I've got a hint from UUID conversion.

Upvotes: 3

victortv
victortv

Reputation: 8892

You can also convert to string during the query:

pipe =
[  
   {  
      "$project":{  
         "_id":0,
         "created":{ "$dateToString":{"format":"%Y%m%dT%H%M", "date":"$created"}},
      }
   }
]
objects = db.aggregate(pipeline=pipe)

Upvotes: 2

Andrew F
Andrew F

Reputation: 2950

PyMongo casts timestamps into the native datetime.datetime structure. You can then use the .isoformat() or .strftime(<format>) methods to convert it to a string.

So, continuing on your example

objects = db.find({}, {"_id": 0, "created": 1})
for obj in objects:
    dt = obj['created']
    time_str = dt.isoformat()
    # ...

Upvotes: 6

Related Questions