Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 759
Michele Avatar asked Dec 03 '18 14:12

Michele


2 Answers

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()
    # ...
like image 148
Andrew F Avatar answered Sep 28 '22 18:09

Andrew F


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)
like image 36
victortv Avatar answered Sep 28 '22 18:09

victortv