pymongoでISODate
pymongoはmongoshellとは似て異なる表記となっており、混乱しますので、雛形の意味も合わせ記事にしました。
pymongoにはISODateは無い;datetime.datetimeを使う
pymongoにはISODateはありません。
datetime.datetimeを用います。
pymongoでISODateフィールドを持つレコードをinsertする例と、日時範囲を指定してfindする例を載せます。
関連手続きを青,mongoDBに渡すレコード、クエリーを赤で強調しました。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coding=utf-8 LF
import pymongo
import datetime
import traceback
import sys
import os
P:bool=True
class HelloDB:
def __init__(self):
self.client: pymongo.mongo_client.MongoClient \
= pymongo.MongoClient(#host =os.environ['DB_HOST'] \
#,username=os.environ['DB_USER'] \
#,password=os.environ['DB_PASSWORD'] \
)
self.db : pymongo.database.Database \
= self.client['hello_DB']
self.col : pymongo.collection.Collection \
= self.db['hello_col']
#end 構築子
def create(self,start_:int,num_:int):
print("create start="+str(start_)+" num="+str(num_))if P else None
self.col.drop()
for _i in range(num_):
_time :int = start_+_i
_timestamp:datetime.datetime= datetime.datetime.fromtimestamp(_time)
_record :dict = {'count':_i,'time':_time,'timestamp':_timestamp}
print("insert : "+str(_record))if P else None
self.col.insert_one(_record)
#end-for
#end-def
def read_with_time(self,start_:int,end_:int):
print("read_with_time start="+str(start_)+" end="+str(end_))if P else None
_query:dict={'$and':[{'time':{'$gte':start_}} \
,{'time':{'$lt':end_}}] }
print("query="+str(_query))if P else None
_cursor: pymongo.cursor.Cursor \
= self.col.find(_query)
_records:list=list(_cursor)
for _record in _records :
print("record = "+str(_record))if P else None
#end-for
#end-def
def read_with_timestamp(self,start_:int,end_:int):
print("read_with_timestamp start="+str(start_)+" end="+str(end_))if P else None
_start:datetime.datetime = datetime.datetime.fromtimestamp(start_)
_end :datetime.datetime = datetime.datetime.fromtimestamp(end_)
print("_start="+str(_start)+" _end="+str(_end))if P else None
_query:dict={'$and':[ {'timestamp':{'$gte':_start}} \
,{'timestamp':{'$lt' :_end }} ]}
print("query="+str(_query))if P else None
_cursor: pymongo.cursor.Cursor \
= self.col.find(_query)
_records:list=list(_cursor)
for _record in _records :
print("record = "+str(_record))if True else None
#end-for
#end-def
#end self地獄
def main():
try:
# 2022-02-01 12:00:00 1643684400
_start:int = 1643684400
_db :HelloDB= HelloDB()
_db.create(_start,10)
_db.read_with_time (1643684403,1643684407)
_db.read_with_timestamp(1643684403,1643684407)
#end-try
except Exception as _e:
print("例外発生:"+str(_e)+"\n"+traceback.format_exc())
sys.exit(1)
#end-except
#end def
if __name__ == '__main__':
main()
#end __main__
実行結果は次のようになります。
$ python3 hello.py
create start=1643684400 num=10
insert : {'count': 0, 'time': 1643684400, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0)}
insert : {'count': 1, 'time': 1643684401, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 1)}
insert : {'count': 2, 'time': 1643684402, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 2)}
insert : {'count': 3, 'time': 1643684403, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 3)}
insert : {'count': 4, 'time': 1643684404, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 4)}
insert : {'count': 5, 'time': 1643684405, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 5)}
insert : {'count': 6, 'time': 1643684406, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 6)}
insert : {'count': 7, 'time': 1643684407, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 7)}
insert : {'count': 8, 'time': 1643684408, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 8)}
insert : {'count': 9, 'time': 1643684409, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 9)}
read_with_time start=1643684403 end=1643684407
query={'$and': [{'time': {'$gte': 1643684403}}, {'time': {'$lt': 1643684407}}]}
record = {'count': 3, 'time': 1643684403, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 3)}
record = {'count': 4, 'time': 1643684404, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 4)}
record = {'count': 5, 'time': 1643684405, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 5)}
record = {'count': 6, 'time': 1643684406, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 6)}
read_with_timestamp start=1643684403 end=1643684407
_start=2022-02-01 12:00:03 _end=2022-02-01 12:00:07
query={'$and': [{'timestamp': {'$gte': datetime.datetime(2022, 2, 1, 12, 0, 3)}}, {'timestamp': {'$lt': datetime.datetime(2022, 2, 1, 12, 0, 7)}}]}
record = {'count': 3, 'time': 1643684403, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 3)}
record = {'count': 4, 'time': 1643684404, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 4)}
record = {'count': 5, 'time': 1643684405, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 5)}
record = {'count': 6, 'time': 1643684406, 'timestamp': datetime.datetime(2022, 2, 1, 12, 0, 6)}
mongo-shellでは次のようになります。
$ mongo
> DBQuery.shellBatchSize=1000000 # おまじない
> use hello_DB
> db.hello_col.find({},{_id:0})
{ "count" : 0, "time" : 1643684400, "timestamp" : ISODate("2022-02-01T12:00:00Z") }
{ "count" : 1, "time" : 1643684401, "timestamp" : ISODate("2022-02-01T12:00:01Z") }
{ "count" : 2, "time" : 1643684402, "timestamp" : ISODate("2022-02-01T12:00:02Z") }
{ "count" : 3, "time" : 1643684403, "timestamp" : ISODate("2022-02-01T12:00:03Z") }
{ "count" : 4, "time" : 1643684404, "timestamp" : ISODate("2022-02-01T12:00:04Z") }
{ "count" : 5, "time" : 1643684405, "timestamp" : ISODate("2022-02-01T12:00:05Z") }
{ "count" : 6, "time" : 1643684406, "timestamp" : ISODate("2022-02-01T12:00:06Z") }
{ "count" : 7, "time" : 1643684407, "timestamp" : ISODate("2022-02-01T12:00:07Z") }
{ "count" : 8, "time" : 1643684408, "timestamp" : ISODate("2022-02-01T12:00:08Z") }
{ "count" : 9, "time" : 1643684409, "timestamp" : ISODate("2022-02-01T12:00:09Z") }
> db.hello_col.find({'$and':[{'time':{'$gte':1643684403}},
{'time':{'$lt':1643684407}}]}
,{_id:0})
{ "count" : 3, "time" : 1643684403, "timestamp" : ISODate("2022-02-01T12:00:03Z") }
{ "count" : 4, "time" : 1643684404, "timestamp" : ISODate("2022-02-01T12:00:04Z") }
{ "count" : 5, "time" : 1643684405, "timestamp" : ISODate("2022-02-01T12:00:05Z") }
{ "count" : 6, "time" : 1643684406, "timestamp" : ISODate("2022-02-01T12:00:06Z") }
> db.hello_col.find({'$and':[{'timestamp':{'$gte':ISODate('2022-02-01 12:00:03')}},
{'timestamp':{'$lt':ISODate('2022-02-01 12:00:07')}}]}
,{_id:0})
{ "count" : 3, "time" : 1643684403, "timestamp" : ISODate("2022-02-01T12:00:03Z") }
{ "count" : 4, "time" : 1643684404, "timestamp" : ISODate("2022-02-01T12:00:04Z") }
{ "count" : 5, "time" : 1643684405, "timestamp" : ISODate("2022-02-01T12:00:05Z") }
{ "count" : 6, "time" : 1643684406, "timestamp" : ISODate("2022-02-01T12:00:06Z") }
> quit()
pymongoでのprint文ではdatetime.datetimeとなり、mongo-shellではISODateとなっていることが分かります。
こまごました事柄
| 固定リンク

