DB Credentials, Python Script, Update last_changed at Startup

Having issues where restarts are resetting last_changed time of numerous entities - so I figured I’d try to hack together a python script that I can execute in an automation upon HA startup to reset the last_changed time of a handful of entities.

After various searches and piecing a number of forum threads together, I’ve unfortunately reached at a stand-still. I’m running Hassio in Docker on a NUC. I’m an Ubuntu NOOB, so used this: https://www.juanmtech.com/set-up-hassio-in-docker-and-in-an-ubuntu-server/ to setup Hassio on the NUC.

I’ve created a /config/python_scripts directory and added :python_script to configuration.yaml

I’ve created a real_last_change.py script (code immediately below) and put it in /config/python_scripts/

import sys
import pymysql.cursors
from datetime import timezone

## entity_id = sys.argv[1]
entity_id  = data.get('entity_id')

mysql_host = '127.0.0.1'
mysql_user = 'user'
mysql_pass = 'pass'
mysql_db   = 'homeassi'

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

db = pymysql.connect (host=mysql_host, user=mysql_user, passwd=mysql_pass, db=mysql_db)
cursor = db.cursor(pymysql.cursors.DictCursor)

sql = """SELECT state,last_changed FROM states WHERE entity_id = '%s'
         ORDER BY created DESC LIMIT 100""" % (entity_id)

cursor.execute(sql)
result = cursor.fetchall()
db.close()

for idx, row in enumerate(result):
    state_act = row['state']
    date_act = row['last_changed']
    if idx == 0:
        state_last = state_act
        date_last = date_act
    if state_last != state_act:
        real_last_changed = date_last
        break
    else:
        state_last = state_act
        date_last = date_act

print(utc_to_local(real_last_changed).strftime('%Y-%m-%d %H:%M:%S'))

I’m trying to execute in developer tools -> services as such:
image

The intended result is to scan the DB and update the entity’s (switch.front_drive_gate) last_changed time to the ACTUAL (not reboot) last time changed.

I’m fairly certain the entity_id = data.get('entity_id') code will correctly used the passed data from the service call correctly, but I can’t, after much searching, figure out what credentials to use to access the DB. Without these, I’m unable to fully test the python script, so could be errors in there I haven’t reached yet.

Anyhow, thanks in advance for any time / help spent / given!

Maybe that helps. :slightly_smiling_face:

1 Like

I think I ‘borrowed’ 99% of the script from this and was hoping that I could call it using the python_script: method - but in further research, found that method disallows import - so I’ll have to go back to your original post and find another way… Sadly I can’t outsmart the limitations, yet…