人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

使用python向MongoDB插入時(shí)間字段的操作

發(fā)布日期:2022-07-11 14:20 | 文章來源:站長之家

看代碼吧~

import pymongo
from dateutil import parser
dateStr = "2019-05-14 01:11:11"
myDatetime = parser.parse(dateStr)
client = pymongo.MongoClient(host="127.0.0.1", port=27017)
db = client["test"]
db.ceshi.insert({"date": myDatetime})
client.close()

補(bǔ)充:python連接mongodb插入數(shù)據(jù)及設(shè)置數(shù)據(jù)類型

安裝 Python MongoDB 驅(qū)動(dòng)程序

安裝驅(qū)動(dòng)

pip install pymongo

檢查

在python交互模式中,執(zhí)行下面的語句

import pymongo
pymongo.version

創(chuàng)建連接

確定 MongoDB 連接串

使用驅(qū)動(dòng)連接到 MongoDB 集群只需要指定 MongoDB 連接字符串即可。

mongodb://數(shù)據(jù)庫服務(wù)器主機(jī)地址:端口號(hào)
mongodb://127.0.0.1:27017

初始化數(shù)據(jù)庫連接

import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017')

數(shù)據(jù)庫操作

初始化數(shù)據(jù)庫和集合

db = client.admin
# 認(rèn)證,如果沒有設(shè)置用戶名和密碼可以忽略此項(xiàng)
db.authenticate('root','password')
# 集合,沒有則創(chuàng)建
collection = db[friend]
# 或
collection = db.friend
# 如果集合名有-存在,在python里識(shí)別不了,所以建議用[]的方式

插入一條新的用戶數(shù)據(jù)

插入數(shù)據(jù)

new_friend = {
"_id": "4519678129565659554",
"user_id": "4519678129565659555",
"friend_user_id": "4519678129565659556",
"remark": "",
"add_time": "2020-07-07T00:39:31.961Z"
}
collection.insert_one(new_friend)

在mongo shell中查看

use admin
db.auth("root","password")
show tables;
db.friend.find({})
-- { "_id" : "4519678129565659554", "user_id" : "4519678129565659555", "friend_user_id" : "4519678129565659556", "remark" : "", "add_time" : "2020-07-07T00:39:31.961Z" }

設(shè)置數(shù)據(jù)的類型

mongo有很多種數(shù)據(jù)類型,這里主要說一下int64和日期時(shí)間

int64,依賴bson

pip install bson

日期時(shí)間,依賴parser

pip install python-dateutil
import bson
from dateutil import parser
aa = {
"_id": bson.int64.Int64("4519678129565659557"),
"user_id": bson.int64.Int64("4519678129565659558"),
"friend_user_id": bson.int64.Int64("4519678129565659559"),
"remark": "",
"add_time": parser.parse("2020-07-07T00:39:31.961Z"),
"_class": "com.aihangxunxi.common.entity.mongo.FriendRelationShip"
}
collection.insert_one(aa)

在mongo shell中查看

db.friend.find({})
-- { "_id" : NumberLong("4519678129565659557"), "user_id" : NumberLong("4519678129565659558"), "friend_user_id" : NumberLong("4519678129565659559"), "remark" : "", "add_time" : ISODate("2020-07-07T00:39:31.961Z") }

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持本站。

海外服務(wù)器租用

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部