Search code examples
pythonmongodbrestflaskisodate

Post date value over REST API to mongoDB and store it as ISOdate


I have a working server that receives data from client machine and stores it into mongoDB. It looks something like

while True:
    data = { "timestamp": datetime.datetime.utcnow().isoformat(),
             "value": get_value(),
           }
    response, content = http.request(url,'POST', json.dumps(data),headers=headers)
    time.sleep(5)

data is sent to the server every 5 seconds. My problem is that the timestamp value is stored as a string and not as ISOdate. How can I store it as ISOdate? or more precisely, how can I change the timestamp value to ISOdate?

Edit: I found a way to convert the values to date in mongo console, but I need to have this done automatically for every new entry.


Solution

  • Can you please try this?

    import datetime
    
    ****
    timestamp = datetime.datetime.utcnow().isoformat()
    isoDate = datetime.datetime.strptime( timestamp, "%Y-%m-%dT%H:%M:%S.%f" )
    print (timestamp)