#Time sensor is on in a time period
1 messages · Page 1 of 1 (latest)
This is for use in a template sensor. AI is, unforuntately, tying itslef up in knots because I don't seem to be able to get the query right
This is the code as I've got it so far... I just can't get the history of the on-time between the start and end.
- sensor:
- name: "Bedroom 2 Cost Yesterday"
unit_of_measurement: "£"
state_class: measurement
state: >
{% set start_time = (now() - timedelta(days=1)).replace(hour=0, minute=0, second=0) %}
{% set end_time = (now() - timedelta(days=1)).replace(hour=23, minute=59, second=59) %}
{% set on_time = -bedroom on-time between start and end goes here- %}
{% set unit_cost = states('input_number.electricity_unit_cost') | float(default=0) %}
{% set heater_power = states('input_number.bedroom_2_consumption') | float(default=0) %}
{% if unit_cost > 0 and heater_power > 0 %}
{{ (((on_time / 3600) * heater_power * unit_cost) / 10000000) | round(2, 'ceil') }}
{% else %}
{{ 0 | round(2) }}
{% endif %}
Then use the state of this sensor directly in your template.
Thanks. I was trying to avoid setting up another sensor... or that was my hope 🙂
So let me get this straight
You have a binary sensor representing a heater's state and are just trying to get a cost to run it for each day?
Yes.
But I'm dynamically changing the times... because if I get up in the morning, I want to know what's happened overnight, which goes across the midnight threshold.
At the moment I have a history stat for each of what I want to read, and if I could get rid of those, it would be a bonus because I've got a number of heaters in the house to monitor.
And then I'm having to use automations to calculate the costs and put them in the final variables, every 10 minutes.
So the way I do this is slightly different
- Template sensor: 0 / power * current electricity price to give a cost/hr
- Integral helper to give a total running cost of the device
- Statistics helper to give the change in the integral in the last 24hrs
If you just want to display it in a graph you can do without 3
Can you share the code for your template sensor please?
{{ states('input_number.power_input') | float(0) * states('sensor.current_electricity_price') | float(0) if states('binary_sensor.active') | bool(false) else 0 }}