Access to historical data in templates without SQL?

This is another request to be able to easily access historical data in templates, similar to Show difference for sensor between current and day before values

While I understand that “create a SQL sensor” is making do with what is available, it feels super clumsy to me. Would it not be possible to have a function similar to:

{{ (historical_states('sensor.outside_temperature'), now() - timedelta( hours = 1)) }}

It could obviously return Unknown/Unavailable if there are no stored values for the time specified, or else interpolate/show the most recent value as the graph does.

This would allow simple comparison with e.g. yesterdays temperature, solar output, etc, without having to understand the internals of SQL storage of a sensor.

Alternatively, presentation of the day’s total value without having to create a helper as well as an automation to update the helper at a specific time, as well as unnecessarily storing the value of the helper in the history.

e.g. a previous poster was trying to track their weight, and show whether they had gained or lost weight compared to the previous day. To do so, they had to create a helper to store the value, as well as an automation to update the helper at the end of the day. This could be trivially replaced with a function similar to that proposed. The time/timedelta argument would also be amenable to things like rounding to the nearest day/hour/timeunit.

Since the code to retrieve historical data already exists, this should be as simple as exposing that code, or a wrapper function that invokes that code, I would think.

Recorder.get_statristics exists. my LLM reports on house state using it. Power, water use, weather v. Power etc…

Allows access to any stats that store stats. (and the doc tells which do)

Thanks for the response. Can the Recorder’s history be accessed from inside a Jinja2 template? I’m not seeing it anywhere.

You have to make the service call in a script or template action section prior to your jinja template. That’s the only way. And before you ask, it’s not possible to add this functionality to just jinja because the service is async where template engine is not. A complete jinja rewrite is needed and that is unlikely to happen. And no, there is no way to add a non async get history to jinja.

2 Likes

Yes. With caveats to said. But absolutely.

From what I can see, the functions available to Jinja2 templating are defined here in homeassistant/helpers/template/__init__.py. e.g.:
self.globals["is_state"] = hassfunction(is_state)

get_significant_states_with_session is in homeassistant/components/recorder/history/__init__.py

A wrapper that looks for a value at or prior to the requested time should not be too hard to implement.

EDIT: Ah, I didn’t see the response about sync vs async before posting this. That would absolutely change things.