pymongo是Python对MongoDB的操作库。但是由于python没有IOSDate类型,所以对Mongo的时间类型是个很麻烦的操作。整理一个把python能识别的date类型转化为IOSDate类型
脚本如下: #!/usr/bin/python import pymongo from dateutil import parser dateStr = '2018-06-12T00:00:00.000Z' myDatetime = parser.parse(dateStr) client = pymongo.MongoClient(host="192.168.2.14",port=29019) db = client.dbs db.authenticate() db.ceshi.insert({'date': myDatetime})
到MongoDB里查看数据:
testin.dbs>db.ceshi.find()
{ "_id" : ObjectId("5b3054fa29e93634dcc21645"), "date" : ISODate("2018-06-12T00:00:00Z") }
已经插入ISODate格式时间。
pymongo查询数据实操:
import pymongo,datetime from dateutil import parser def findmongo(): time1 = datetime.datetime.now() dateStr1 = '2019-01-21T00:00:00Z' dateStr2 = '2019-01-23T00:00:00Z' myDatetime1 = parser.parse(dateStr1) myDatetime2 = parser.parse(dateStr2) client = pymongo.MongoClient(host="0.0.0.0", port=3717) db = client.mongolilly db.authenticate("root","admin") a = db.current_temp.find({"order_id":"465","scan_time":{ "$gte": myDatetime1, "$lte":myDatetime2}}) time2 = datetime.datetime.now() time3 = time2 - time1 print "time3------->select_time :%s" % time3 list = [] for i in a : data = { "number": i["number"], "temperature": i["temperature"], "scan_time": i["scan_time"], "scan_location": i["scan_location"], "battery": i["battery"], "rssi": i["rssi"], "mac": i["mac"], "order_id": i["order_id"] # "id": str(one_info.id) } list.append(data) time4 = datetime.datetime.now() time5 = time4-time1 print "time5------>all_time:",time5