1

I am new to MongoDB and Python thus struggling with something that I'm sure is quite simple to do. In my collection (sample below), I have the date and time stored as a string. I need to convert them to Date (ISODate?) and Time data types so I can use built in MongoDB operators.

For example, I want to use the $dayofWeek operator to find out whether a date is a weekday or weekend but I can't do that while it is a string.

Ideally I would like guidance on how to accomplish this in Python (using Pymongo). If that is too cumbersome, I can do it using the mongo shell. Appreciate any help!

{
"_id" : ObjectId("xyz"),
"Date" : "12/9/17", 
"Time" : "03:31:40", 
"Speaker" : "Joe", 
"Text" : "‎Sample Text"
}
khansar
  • 11
  • 2

1 Answers1

2

A sample snippet in python.

> d = "12/9/17"   
> t = "03:31:40"   
> dt = d + " " + t   
> datetime_obj = datetime.strptime(dt,'%m/%d/%y %H:%M:%S')   
> print datetime_obj   
2017-12-09 03:31:40

And then just insert this object into your collection: db['dates'].insert({"date" : d}) Or whatever way you are inserting your data into mongo.