python-3.x - 我怎样才能不断改变时间
问题描述
大家好,我对python很陌生,非常感谢在这件事上提供一些帮助,我一直在尝试获取我发送到数据库的每条记录的实际时间,但我认为因为它是一个循环,它似乎记录了开始时间并循环它。
有人可以帮我解决这个问题吗?
我怎样才能获得实时而不是在同一时间循环
# Author: Aswin Ramamchandran
# Version: 1.1
from time import sleep
import datetime
import pymongo
import time
# This URL provides connection to the database
uri = blahblah
# initialising pymongo client
client = pymongo.MongoClient(uri)
# Database where the records will be saved - reference to the database
db = client.Kostenanalyse
# Accessing the collection "latenz" from the Database
coll = db.latenz
#Defining the Start time
start_time = datetime.datetime.now()
start_time = start_time.isoformat()
end = time.perf_counter()
def create_latenz_data()-> dict:
return {
"Temperature" : "",
"Time when packet was sent" : start_time,
"Sensor A reading" : "",
"Latency" : end,
}
#While loop
while True:
data = create_latenz_data()
start = time.perf_counter()
coll.insert_one(data)
end = time.perf_counter() - start
print('{:.6f}s for the calculation'.format(end))
print(str(start_time) + 'Wrote data sample {} to collpipection {}'.format(data, 'latenz'))
sleep(0.5)
解决方案
您的脚本start_time
在加载时存储变量并且不会更改它。由于您在 while 循环和 inside 中使用了相同的变量,因此直接create_latenz_data()
替换start_time
为,datetime.datetime.now().isoformat()
因此每次调用时都会选择新时间。
from time import sleep
import datetime
import pymongo
import time
# This URL provides connection to the database
uri = blahblah
# initialising pymongo client
client = pymongo.MongoClient(uri)
# Database where the records will be saved - reference to the database
db = client.Kostenanalyse
# Accessing the collection "latenz" from the Database
coll = db.latenz
def create_latenz_data()-> dict:
return {
"Temperature" : "",
"Time when packet was sent" : datetime.datetime.now().isoformat(),
"Sensor A reading" : "",
"Latency" : end,
}
#While loop
while True:
data = create_latenz_data()
start = time.perf_counter()
coll.insert_one(data)
end = time.perf_counter() - start
print('{:.6f}s for the calculation'.format(end))
print(str(datetime.datetime.now().isoformat()) + 'Wrote data sample {} to collpipection {}'.format(data, 'latenz'))
sleep(0.5)
推荐阅读
- nestjs - “NestExpressApplication”类型上不存在属性“注册”
- c++ - 在 Unix 上用 C++ 打开文件:我们可以避免区分大小写吗?
- python - ValueError: 层 max_pooling2d_12 的输入 0 与层不兼容:预期 ndim=4,发现 ndim=0。收到的完整形状:[]
- ruby-on-rails - Ruby 地理编码器:在同一模型上对第二组坐标进行地理编码
- json - Controller 如何将 JSON 数据从 AJAX 转换为 Model 实例?
- python - 如何遍历 python DICT 以提取特定键的特定值?
- c# - PtrToStructure C# 中的空引用异常
- c# - 照明亮度的 Lerp 不会逐渐增加
- c# - 在 IHttpHandler 中检测远程端口
- excel - Excel 宏运行但未显示在开发人员选项卡中