Quickly solve the time zone problem of pymongo operating mongodb

  • 2021-08-17 00:14:37
  • OfStack

As shown below:

1. The date and time format of mongodb is UTC time, China time = UTC time +8

2. Add a time zone to the pymongo client to solve this problem:


import pytz
from pymongo import MongoClient
from datetime import datetime
tzinfo = pytz.timezone('Asia/Shanghai')

client = MongoClient(
  host="127.0.0.1",
  port=27017,
  username="root",
  password="123456",
  authSource="admin", #  Which database to authenticate in, the default is admin
  tz_aware=True, #  Set to True
  tzinfo=tzinfo  #  Add time zone information 
)
db = client["test"]
collection = db["mytest"]

datetime.now() # 2020-04-11 10:42:42.452433
ret = collection.insert_one({
  "name": " Test 5",
  "create_time": tzinfo.localize(datetime.now()) 
})
# create_time Can't be used datetime.now() Get the time, 
#  You should use the  datetime.utcnow() Or  tzinfo.localize(datetime.now()) Or  datetime.now(tz=tzinfo)
#  In this way, the date and time when reading data is the standard Chinese time 
res = collection.find_one({"name": " Test 5"})
print(res)
# {'_id': ObjectId('5e912ea261d252f76350728a'), 'name': ' Test 5', 'create_time': datetime.datetime(2020, 4, 11, 10, 42, 42, 452000, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)}

#  The following test directly uses the datetime.now() The situation of 
datetime.now() # 2020-04-11 10:49:41.899445
collection.insert_one({
  "name": " Test 6",
  "create_time": datetime.now()
})
res = collection.find_one({"name": " Test 6"})
# {'_id': ObjectId('5e913045143015041d776d08'), 'name': ' Test 6', 'create_time': datetime.datetime(2020, 4, 11, 18, 49, 41, 899000, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)}
#  You can see the time +8 Hours 

Additional knowledge: pymongo queries by time

I won't talk too much, let's just look at the code ~


from pymongo import MongoClient 
client=MongoClient('localhost',27017)
db=client.adv.message
from datetime import datetime
import pandas as pd
#db.insert_one({'player_id':js2['player_id'],'message':js2['message'],
#        'label':label,'predict_time':datetime.datetime.now()})

# Query by time 
q1={"predict_time":{"$gte" :datetime(2019,9,25) ,"$lte": datetime(2019,9,28)}}  
l1=list(db.find(q1))

#l1=list(db.find({}))
df=pd.DataFrame(l1)

Related articles: