pengz
pengz

Reputation: 2471

Convert MongoDB Date format to String in Python (without using dateToString)

I would like to convert a MongoDB Date Object to a string.

However, I am unable to use the "dateToString" operator because I am running MongoDB 2.6 and do not have the option to upgrade at this time.

What should I use instead?

Query:

computer = db['cmp_host'].aggregate([
        {"$project":{
            "u_ipv4": "$addresses.ipv4",
            #"u_updated_timestamp": "$last_seen",
            #"u_updated_timestamp": { $dateToString: { format: "%Y-%m-%d", date: "$last_seen" } }
            }
         }
        ])

Current MongoDB Date format (needs to be converted to human readable string):

datetime.datetime(2016, 9, 2, 12, 5, 18, 521000)

Upvotes: 0

Views: 2496

Answers (1)

kevinadi
kevinadi

Reputation: 13805

The datetime.datetime(2016, 9, 2, 12, 5, 18, 521000) is a Python datetime type, not MongoDB's.

To convert it into a string, you can use Python datetime's strftime() method. For example:

>>> d = datetime.datetime(2016, 9, 2, 12, 5, 18, 521000)

>>> d.strftime('%Y-%m-%d')
'2016-09-02'

>>> d.strftime('%c')
'Fri Sep  2 12:05:18 2016'

The full description of strftime() is here: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Upvotes: 2

Related Questions