Thursday, February 3, 2022

[SOLVED] My date stamp in the database is not changing. Python / MariaDB

Issue

My first project, so there is a heavy noob alert here :) I am building a weather station on my Raspberry Pi. Python.

I am trying to store my weather observations in a database. Everything is uploaded fine, but the date is not changing. I think there might be something wrong with my loop?

import time
import bme280_sensor
import ds18b20_therm
import database

interval = 5

temp_probe = ds18b20_therm.DS18B20()

db = database.weather_database()

while True:
    start_time = time.time()
    while time.time() - start_time <= interval:
        ground_temp = temp_probe.read_temp()
        humidity, pressure, ambient_temp = bme280_sensor.read_all()
        print(humidity, pressure, ambient_temp, ground_temp)
        db.insert(ambient_temp, ground_temp, pressure, humidity)

This is a snippet from my database.py

def insert(self, ambient_temperature, ground_temperature, air_pressure, humidity, created = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")):
    params = ( ambient_temperature,
        ground_temperature,
        air_pressure,
        humidity,
        created )
    print(self.insert_template % params)
    self.db.execute(self.insert_template, params)

Solution

In the definition of insert

def insert(self, ambient_temperature, ground_temperature, air_pressure, humidity, created = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")):

the default value of created is only evaluated once, when the interpreter first reads the function definition. A better approach would be to set a default of None, and override it in the function body.

def insert(self, ambient_temperature, ground_temperature, air_pressure, humidity, created=None):
    if created is  None:
        created = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")


Answered By - snakecharmerb
Answer Checked By - Marie Seifert (WPSolving Admin)