You need to enable JavaScript to run this app. Python循环写入MongoDB时如何获取每条数据的实时发送时间
优惠活动
大模型
产品
解决方案
定价
更多

Python循环写入MongoDB时如何获取每条数据的实时发送时间

问题核心原因
  • 代表数据包发送时间的start_time写在了全局代码块里,程序一启动就把这个变量赋值为当时的时间,后续循环运行时从来没有重新计算过这个值,属于固定不变的常量
  • 生成待写入数据的create_latenz_data()函数直接读取这个全局固定值,不管循环执行多少次,所有生成的数据用的都是同一个程序启动时刻的时间
  • 存在同逻辑的隐藏bug:全局提前定义的end = time.perf_counter()是程序启动时的计时基准值,第一次写入数据库时这个值就被固定了,后续循环计算出来的写入延时差,没有同步更新到待写入的数据库记录里
具体调整方案
  • 把实时时间的获取逻辑挪到循环内部,每次执行到数据生成、数据库写入步骤时,才调用datetime.datetime.now().isoformat()获取当次的数据包发送时间,不要在程序启动时就提前算好固定值
  • 修改create_latenz_data()函数,让它接收当次实时计算的发送时间、写入延时值作为入参,不再直接读取全局的固定变量
  • 修正日志输出的取值逻辑,用当次循环生成的实时时间打日志,不要硬引用全局的固定时间值
修正后的可运行代码
# 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

def create_latenz_data(packet_send_time: str, latency: float) -> dict:
    return {
        "Temperature": "",
        "Time when packet was sent": packet_send_time,
        "Sensor A reading": "",
        "Latency": latency,
    }

# While loop 
while True:
    # 每次循环到此处,才实时计算当前的数据包发送时间
    current_packet_time = datetime.datetime.now().isoformat()
    start = time.perf_counter()
    
    # 生成待写入的基础数据,latency先设为初始值0
    data = create_latenz_data(current_packet_time, 0.0)
    
    coll.insert_one(data)
    
    # 计算本次数据库写入的实际耗时
    current_latency = time.perf_counter() - start
    # 将算好的耗时更新到待写入的数据中
    data["Latency"] = current_latency
    
    print(f'本次计算耗时: {current_latency:.6f}s')
    print(f'{current_packet_time} 已将数据样例写入集合latenz: {data}')
    sleep(0.5)

内容的提问来源于stack exchange,提问作者python3 aswin.py

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.01 04:06:05