Adding State Changed to Devices / Lights / Sensors

Hi

I am sure this has come up before, but I cant seem to find anything to help me.

What i am looking to do is the following

  • Show when the door was last opened / closed :

  • Show then the light as last used ?

Any anyone help or point me in the right direction

Thanks

If you have them as part of an automation then you can simply do the following to get the timestamp of when they were last triggered:

{{ states.automation.turn_on_dining_room_lights.attributes.last_triggered }}

As per @benji87, however if you don’t use it as part of an automation, then you’d need to create a small script that extracts the info from your DB.
if you want/need I can share my script to retrieve such info. Let me know

Hi Mate that would be great if you could share help me learn the more advanced stuff :wink:

Thanks appreciate it…

here is the script:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb
from dateutil import tz

from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Europe/London')

try:
	con = mdb.connect(sqlhost, sqlusername, sqlpassword, sqltable)
	cur = con.cursor()
	cur.execute("SELECT `last_updated` FROM `states` WHERE `entity_id` = 'sensor.xiaomi_status' and `state` = 'Cleaning' order by `state_id` DESC limit 1")
	rows = cur.fetchone()
	MyLastSeen = rows[0]
	con.close()
except:
	print "Unable to connect to HASS SQL Table (%s)" % datetime.datetime.now().strftime("%d/%m/%y %H:%M")

#convert UTC to British Time
MyLastSeen = MyLastSeen.replace(tzinfo=from_zone)
MyLastSeen = MyLastSeen.astimezone(to_zone)
print "%s" % MyLastSeen.strftime("%d/%m/%y %H:%M")

Then create a sensor:

- platform: command_line
  name: Last Clean
  command: "/home/USER/.homeassistant/shell_scripts/xiaomi_last_clean.py"