No luck
last_changed2 = self.entities[device][entity]["last_changed"]
KeyError: 'binary_sensor'
No luck
last_changed2 = self.entities[device][entity]["last_changed"]
KeyError: 'binary_sensor'
hmm you are right.
self.entities seems to be an object
self.entities.binary_sensor works
so if all your entities are binary sensors then you could use:
device, entity = self.split_entity(self.args["door"])
binary_sensors = self.entities.binary_sensors
last_changed = binary_sensors[entity]["last_changed"]
Probably a bit late for the party, but I managed to make it work with variables like this:
self.occupancy_sensor = 'binary_sensor.room_occupancy_{}'.format(self.room)
occupancy_state = self.get_state(self.occupancy_sensor, attribute='all')
if occupancy_state['state'] == 'on':
return
time_off = datetime.now().timestamp() - self.convert_utc(occupancy_state['last_changed']).timestamp()
by just getting the state with attribute="all"
you can access all the keys, which seems to be more flexible than self.entities
New to python. This works for me ,but I have a more complicated issue. I’m trying to find out how long someone was away from home to set different greetings. Everything is working except I need to gather the information on how long they were away from home.
When I use last_changed it tells me the time from a few moments ago since they just got home. How can I get the time before last_changed?
by listening to the state that the entity changes from home to not_home and then store that time in a variable, so you can reuse it when the state changes from not_home to home.
There’s a newer way to do this now which gives you the time elapsed in seconds since the last change
o_entity = self.get_entity('sensor.name')
age = o_entity.last_changed_seconds