首页 > 解决方案 > 我怎样才能不断改变时间

问题描述

大家好,我对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) 

标签: python-3.xazure-cosmosdbpython-datetime

解决方案


您的脚本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) 

推荐阅读