@vazquezjm wrote:
Hi.
I’m trying to simplify the way I get the number of minutes a device was ‘on’. Currently, I’m using a SQL query to get the minutes from the SQLite DB, but I’m pretty sure there has to be another way.
So, my sensor template looks like this:
- platform: sql queries: - name: panel_minutes_today query: "SELECT (SUM(Interval) / 60) As panel_minutes FROM (SELECT CAST((JulianDay(T2.created) - JulianDay(T1.created)) * 24 * 60 * 60 As Integer) AS Interval FROM states T1 JOIN states T2 ON T1.entity_id = T2.entity_id AND T2.created > T1.created AND T2.state = 'off' WHERE T1.entity_id = 'switch.panel_oficina' AND T1.state = 'on' AND date(T1.created) = date('now') GROUP BY T1.entity_id, T1.state, T1.created) t;" column: 'panel_minutes'
SQL query for easier reading:
SELECT (SUM(Interval) / 60) As panel_minutes FROM ( SELECT CAST((JulianDay(T2.created) - JulianDay(T1.created)) * 24 * 60 * 60 As Integer) AS Interval FROM states T1 JOIN states T2 ON T1.entity_id = T2.entity_id AND T2.created > T1.created AND T2.state = 'off' WHERE T1.entity_id = 'switch.panel_oficina' AND T1.state = 'on' AND date(T1.created) = date('now') GROUP BY T1.entity_id, T1.state, T1.created ) t;
As you might noticed, I use the
states
table and based on thestate
field (‘on’ and ‘off’) I count the seconds between the two dates, then convert to minutes.This approach works but has a pitfall (probably more) and it is the scenario where the start date is on Date A but the end date is on Date B (where Date B = Date A + day).
Is there a better approach to get the time in minutes a device worked on a given date?
TIA
Posts: 1
Participants: 1