Real state last_changed

I modified it a little, so it should run in hass.io too.

The sensor example:

sensor:
  - platform: command_line
    name: "RLC MQTT Test Switch"
    command: "python3 scripts/real_last_change.py switch.mqtt_test"
    scan_interval: 60

The script lives in /config/scripts/real_last_change.py

import sys
import MySQLdb
from datetime import timezone

entity_id = sys.argv[1]

## Use the settings from recorder config in configuration.yaml
#recorder:
#  db_url: mysql://user:[email protected]/hadb?charset=utf8
mysql_user = 'user'
mysql_pass = 'pass'
mysql_host = '127.0.0.1'
mysql_db   = 'hadb'

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

db = MySQLdb.connect (host=mysql_host, user=mysql_user, passwd=mysql_pass, db=mysql_db)
cursor = db.cursor(MySQLdb.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()

if len(result) > 0:
    real_last_changed = None
    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

    if real_last_changed:
        print(utc_to_local(real_last_changed).strftime('%d.%m.%Y %H:%M:%S'))
    else:
        print('No state change for: ' + entity_id)
else:
    print('No states for: ' + entity_id)
3 Likes