Johnny John Boy
Johnny John Boy

Reputation: 3222

Updating MongoDB Date in String to Date Format

I am re-asking this question as there seemed to be some misunderstanding. I need to convert a string in my mongo to a date format using Python. I have the following code:

newest_date = datetime.strptime(r["date"], "%Y-%m-%d").isoformat()

Which successfully created the following date object (new_date):

2017-01-03T00:00:00

When I try:

db.address.update_one({"address": "1234", {"$set": {"date" : new_date}})

I get the item updated in the document but it's still a string, not a date. I can successfully do it in the shell using:

db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){  element.date = ISODate(element.date); db.address.save(element);})

How can I update the actual type to be a date because when I do it from the console I get the output:

"date": {"$date": "2017-06-28T00:00:00.000Z"

},

Upvotes: 0

Views: 1373

Answers (1)

Johnny John Boy
Johnny John Boy

Reputation: 3222

Hopefully this will help someone not make the stupid mistake I made. Make sure you don't append .isoformat() to a datetime object like a clown...

newest_date = datetime.strptime(r["date"], "%Y-%m-%d")

Upvotes: 1

Related Questions