neumear
neumear

Reputation: 121

python - Loop outputs same timestamp every time

I have this code where I reads outputs from other scripts then inputs those in a database. Additionally, a timestamp is added.

    import time
    import os
    import subprocess
    import sys
    from time import sleep
    import datetime
    import sqlite3
    import fnmatch, shutil

    sensorID = "1"
    dbname = 'sensorsData.db'

    t = time.localtime()
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S', t)


    refresh = 300 #time in seconds , getting new data from sensors

    #get data from sensor
    def gettemp():
        temp = subprocess.check_output("sudo python /home/pi/AIRQMONITOR/temp.py", shell=True)
        print(timestamp)
        return(temp)
    def getpm25():
        pm25 = subprocess.check_output("sudo python /home/pi/AIRQMONITOR/pm2.py", shell=True)
        return (pm25)
    def getpm10():
        pm10 = subprocess.check_output("sudo python /home/pi/AIRQMONITOR/pm10.py", shell=True)
        return (pm10)
    def getco():
        co = subprocess.check_output("sudo python /home/pi/AIRQMONITOR/co.py", shell=True)
        return(co)
#log data
    def logdata(temp,co,pm25,pm10):
        conn = sqlite3.connect(dbname)
        curs=conn.cursor()
        curs.execute("INSERT INTO sensors values(?,?,?,?,?)", (timestamp, temp, co, pm25, pm10))
        curs.execute("INSERT INTO temperatures values(?,?,?)", (timestamp, sensorID, temp ))
        curs.execute("INSERT INTO co values(?,?,?)", (timestamp, sensorID, co ))
        curs.execute("INSERT INTO pm25 values(?,?,?)", (timestamp, sensorID, pm25 ))
        curs.execute("INSERT INTO pm10 values(?,?,?)", (timestamp, sensorID, pm10 ))
        conn.commit()
        conn.close()

#main
    def main():
        while True:
            temp = gettemp()
            pm25 = getpm25()
            pm10 = getpm10()
            co = getco()
            logdata(temp, co, pm25, pm10)
            time.sleep(refresh)

#-----execute program... gooo!
main()

But, at every loop, the same timestamp from the first run is outputted:

terminal outputs showing same timestamp after 3 loops

How can this be? Thanks in advance!

Upvotes: 1

Views: 1564

Answers (4)

Charif DZ
Charif DZ

Reputation: 14721

timestamp is used in several method so define it as a global variable in the main method to be able to update its value and Reset timestamp inside the while loop in each iteration:

def main():
    global timestamp 
    while True:
       timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
       temp = gettemp()
       pm25 = getpm25()
       pm10 = getpm10()
       ...
       ...

But keep the first lines at the top of the file to keep timestampa global variable:

sensorID = "1"
dbname = 'sensorsData.db'

# temestamp should stay a global variable
timestamp = None

Upvotes: 1

Mohsen_Fatemi
Mohsen_Fatemi

Reputation: 3401

You need to create a function to calculate time stamp, let's say get_timestamp() :

def get_timestamp():
    t = time.localtime()
    return time.strftime('%Y-%m-%d %H:%M:%S', t)

after that you need to call get_timestamp in your main function :

def main():
    while True:
        temp = gettemp()
        pm25 = getpm25()
        pm10 = getpm10()
        co = getco()
        timestamp = get_timestamp()
        logdata(temp, co, pm25, pm10,timestamp)
        time.sleep(refresh)

all you need now is to change the logdata so that it takes timestamp as input :

def logdata(temp,co,pm25,pm10,timestamp):
    conn = sqlite3.connect(dbname)
    curs=conn.cursor()
    curs.execute("INSERT INTO sensors values(?,?,?,?,?)", (timestamp, temp, co, pm25, pm10))
    curs.execute("INSERT INTO temperatures values(?,?,?)", (timestamp, sensorID, temp ))
    curs.execute("INSERT INTO co values(?,?,?)", (timestamp, sensorID, co ))
    curs.execute("INSERT INTO pm25 values(?,?,?)", (timestamp, sensorID, pm25 ))
    curs.execute("INSERT INTO pm10 values(?,?,?)", (timestamp, sensorID, pm10 ))
    conn.commit()
    conn.close()

and remove the following lines from your code :

t = time.localtime()
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', t)

Upvotes: 1

rokuda
rokuda

Reputation: 24

I'd guess the problem is that you would need to call the used function

timestamp = time.strftime('%Y-%m-%d %H:%M:%S', t)    

every time the outer function is called, but you just save the value of this specific point in time and print it repeatedly.

def gettemp():
    temp = subprocess.check_output("sudo python /home/pi/AIRQMONITOR/temp.py", shell=True)
    print(time.strftime('%Y-%m-%d %H:%M:%S', t) )
    return(temp)

This should work out.

Upvotes: 1

Ofer Sadan
Ofer Sadan

Reputation: 11932

You run these lines at the start of your code:

t = time.localtime()
timestamp = time.strftime('%Y-%m-%d %H:%M:%S', t)

These only run once (not in a loop) and the timestamp in them never changes. If you want to update the timestamp you should make those lines part of your loop, or better yet, use a function:

def get_timestamp():
    t = time.localtime()
    return time.strftime('%Y-%m-%d %H:%M:%S', t)

And replace every time you try to use timestamp with get_timestamp()

Upvotes: 4

Related Questions