Convert MongoDB Date format to String in Python (without using dateToString)
<p>I would like to convert a MongoDB Date Object to a string.</p>

<p><strong>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.</strong></p>

<p>What should I use instead?</p>

<p>Query:</p>

<pre><code>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" } }
            }
         }
        ])
</code></pre>

<p>Current MongoDB Date format (needs to be converted to human readable string):</p>

<pre><code>datetime.datetime(2016, 9, 2, 12, 5, 18, 521000)
</code></pre>

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

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

<pre><code>&gt;&gt;&gt; d = datetime.datetime(2016, 9, 2, 12, 5, 18, 521000)

&gt;&gt;&gt; d.strftime('%Y-%m-%d')
'2016-09-02'

&gt;&gt;&gt; d.strftime('%c')
'Fri Sep  2 12:05:18 2016'
</code></pre>

<p>The full description of <code>strftime()</code> is here: <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior</a></p>

python mongodb date