脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 使用python向MongoDB插入时间字段的操作

使用python向MongoDB插入时间字段的操作

2021-11-05 08:55fiery_heart Python

这篇文章主要介绍了使用python向MongoDB插入时间字段的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

看代码吧~

?
1
2
3
4
5
6
7
8
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()

补充:python连接mongodb插入数据及设置数据类型

安装 Python MongoDB 驱动程序

安装驱动

?
1
pip install pymongo

检查

在python交互模式中,执行下面的语句

?
1
2
import pymongo
pymongo.version

创建连接

确定 MongoDB 连接串

使用驱动连接到 MongoDB 集群只需要指定 MongoDB 连接字符串即可。

?
1
2
mongodb://数据库服务器主机地址:端口号
mongodb://127.0.0.1:27017

初始化数据库连接

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

数据库操作

初始化数据库和集合

?
1
2
3
4
5
6
7
8
db = client.admin
# 认证,如果没有设置用户名和密码可以忽略此项
db.authenticate('root','password')
# 集合,没有则创建
collection = db[friend]
# 或
collection = db.friend
# 如果集合名有-存在,在python里识别不了,所以建议用[]的方式

插入一条新的用户数据

插入数据

?
1
2
3
4
5
6
7
8
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中查看

?
1
2
3
4
5
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" }

设置数据的类型

mongo有很多种数据类型,这里主要说一下int64和日期时间

int64,依赖bson

?
1
pip install bson

日期时间,依赖parser

?
1
pip install python-dateutil
?
1
2
3
4
5
6
7
8
9
10
11
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中查看

?
1
2
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") }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/fiery_heart/article/details/90229610

延伸 · 阅读

精彩推荐