Time since last update

I am trying to write a script and I need the time delta since a sensor.state has been updated. For that I need the current time in the same timezone as the sensor update, which I believe is UTC.

I found two options:

  1. https://home-assistant.io/blog/2015/05/09/utc-time-zone-awareness/
    and
  2. https://home-assistant.io/components/sensor.time_date/

The first one does not seem to work in a script:
now = hass.util.dt.utcnow()
gives
Error executing script: Not allowed to access HomeAssistant.util

The second option gives me a time in str format, not a timestamp so I cannot subtract. And I am also not able to slice the string using [:2] or so. Can anyone help me?

[edit]
What I need it for? I want to start the exhaust fan of the bathroom a minute after the boiler status has changed to HW (hot water)

I use the last_updated attribute like this

  - platform: template
    sensors:
      lastupdated:
        value_template: '{{relative_time(states.device_tracker.XXXX.last_updated)}}'
        entity_id: sensor.time
4 Likes

Somehow relative_time did not give me reasonable results, and due to the formatting I was not able to do math (gave me 19 seconds <== including the seconds).

I managed to get it to work by doing this:

alias: "Fan Speed HW"
trigger:
  platform: mqtt
  topic: /woonkamer/woonkamer/thermostaat/boilerstatus
  payload: "HW"
condition:
  condition: template
  value_template: '{{ as_timestamp(now()) - as_timestamp(states.sensor.wk_boilerstatus.last_changed) > 120}}'
action:
  service: python_script.fanspeed
  data_template:
    trigger_type: "HW"

Why I do this? Because my boiler sends a “Hot Water” signal once per hour, maybe to keep a small amount of water hot. I don’t want the fan to start running for that reason. I have another automation that activates on high humidity. It could have been combined but this was easier :slight_smile:

Summary
Summary

This text will be hidden

Hey I’m looking for script example, but your talk about boiler is interesting. What kind of boiler do you use ?

I am using a Nefit heater/boiler combo in combination with a Nefit Easy thermostat. These models are sold in the Netherlands and I believe also in Germany.

A Python script sends a mqtt status update every now and then. https://github.com/patvdleer/nefit-client-python

I am not home at the moment and also still working on the code. Will post when it is in a usable state.

stumbled across this - @Hydreliox you may be interested in the code & circuit I wrote to read from Nefit/Bosch EMS boilers EMS-ESP-Boiler

1 Like