[SOLVED] Template sensor giving unknown but developer template shows true

device_class: timestamp requires a date. Your logs will tell you why it’s not working.

I.e. Your template is fine, where you’re using it is not.

Thanks for your assistance. Much appreciated!

Can you help me with a fix? I need to create a time sensor from an input_datetime

I’ve tried:

template:
  - sensor:
      name: test
      device_class: timestamp
      state: {{ state_attr("input_datetime.alarm_time", "timestamp") | timestamp_custom("%H.%M", False) }}

Again - works in template but configuration.yaml doesn’t like it due to “missed comma between flow collection entries”

you’re missing outside quotes for your template. Use the multiline yaml notation or ensure your outside quotes are wrapped around your template. Also make sure outside quotes and inside quotes are different, i.e. " outside and ' inside.

Template show correct in developer tool template editor, but error in configuration ?

TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ ((states.sensor.varmepumpe_total_daily_energy.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}' but no default was specified') while processing template 'Template("{{ ((states.sensor.varmepumpe_total_daily_energy.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}")' for attribute '_attr_native_value' in entity 'sensor.varmepumpe_kost_daglig'
TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ ((states.sensor.varmepumpe_forbruk_mnd.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}' but no default was specified') while processing template 'Template("{{ ((states.sensor.varmepumpe_forbruk_mnd.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}")' for attribute '_attr_native_value' in entity 'sensor.varmepumpe_kost_mnd'
TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ ((states.sensor.easse_forbruk_kwh_dag.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}' but no default was specified') while processing template 'Template("{{ ((states.sensor.easse_forbruk_kwh_dag.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}")' for attribute '_attr_native_value' in entity 'sensor.ladebil_kost_daily'
TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ ((states.sensor.easse_forbruk_kwh_mnd.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}' but no default was specified') while processing template 'Template("{{ ((states.sensor.easse_forbruk_kwh_mnd.state | float) * (states.sensor.strompris_kwh.state | float)) | round(2) }}")' for attribute '_attr_native_value' in entity 'sensor.ladebil_kost_mnd'
TemplateError('TypeError: is_state() takes 3 positional arguments but 4 were given') while processing template 'Template("{% if is_state('sensor.washing_machine_status','Running','Finishing') %} Running {% else %} Finishing {% endif %}")' for attribute '_attr_native_value' in entity 'sensor.vaskemaskin_status'

Many filters (including float) require assigned defaults as of 2012.10

From Templating Docs:

WARNING

Avoid using states.sensor.temperature.state , instead use states('sensor.temperature') . It is strongly advised to use the states() , is_state() , state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).

Thanks , Seem template is little bit correct now as documentation. what you think ?
How can i manage to only 2 digits after decimal.

{{ states( 'sensor.varmepumpe_total_daily_energy' ) | float * states( 'sensor.strompris_kwh' ) | float | round(2) }}

Extra set of brackets. You’re just rounding the kWh figure. Here it is with the defaults added too:

{{ (states('sensor.varmepumpe_total_daily_energy')|float(0)*states('sensor.strompris_kwh')|float(0))|round(2) }}

Thanks, but still error

Configuration invalid!

Error loading /config/configuration.yaml: invalid key: "OrderedDict([("(states('sensor.gangen_varmeovn_cal_energy_hourly')| float(0)*states('sensor.strompris_kwh')|float(0))|round(2)", None)])"
in "/config/packages/Varmeapparater/ganagen_varmeovn.yaml", line 49, column 0

My Template is:

value_template: {{ (states('sensor.gangen_varmeovn_cal_energy_hourly')|float(0)*states('sensor.strompris_kwh')|float(0))|round(2) }}

You need to surround a single-line template in double quotes. See the important rules in this page:

Because your template uses single quotes, surround it with double quotes.

Do you mean like

value_template: {{ (states("sensor.gangen_varmeovn_cal_energy_hourly")|float(0)*states("sensor.strompris_kwh")|float(0))|round(2) }}

No. Like this:

value_template: "{{ (states('sensor.gangen_varmeovn_cal_energy_hourly')|float(0)*states('sensor.strompris_kwh')|float(0))|round(2) }}"

After i use double quotes, an other error popup

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected char "'" at 71) for dictionary value @ data['sensors']['gangen_varmeovn_kost_idag']['value_template']. Got "{{ states('sensor.gangen_varmeovn_cal_energy_daily')| float(0)*(states('sensor.strompris_kwh | float(0)) | round(2) }}". (See ?, line ?).
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['varmepumpe_time_pris']['value_template']. Got "{{ states('sensor.gangen_varmeovn_cal_energy_hourly')| float(0)*states('sensor.strompris_kwh')|float(0))|round(2) }}". (See ?, line ?).

I dont know why i have to use 2 different syntax in same type template ? one is valid with float(0)) and other is valid with float(0)


if i delete extra ) like float(0) then then template is valid

value_template: "{{ states('sensor.varmepumpe_forbruk_mnd')|float(0)*states('sensor.strompris_kwh')|float(0))|round(2) }}"

ERROR

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['varmepumpe_kost_mnd']['value_template']. Got "{{ states('sensor.varmepumpe_forbruk_mnd')|float(0)*states('sensor.strompris_kwh')|float(0))|round(2) }}". (See ?, line ?).

if i add extra ) like float(0)) then then template is valid

value_template: "{{ (states('sensor.gangen_varmeovn_cal_energy_hourly')|float(0)*states('sensor.strompris_kwh')|float(0)|round(2) }}"

ERROR

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensors']['gangen_varmeovn_time_pris']['value_template']. Got "{{ (states('sensor.gangen_varmeovn_cal_energy_hourly')|float(0)*states('sensor.strompris_kwh')|float(0)|round(2) }}". (See ?, line ?).

Please post the entire code of the sensor. If this is a template sensor using the modern format, you should use state not value_template — but without the whole code we’re wasting time guessing.
Have a look at the excellent documentation (here, for example).

For the template itself, the brackets aren’t just something you randomly sprinkle in to see if it works. It can help to space things out a bit to understand what’s going on. Here’s the template from my prior post, and then again spaced out:

{{ (states('sensor.gangen_varmeovn_cal_energy_hourly')|float(0)*states('sensor.strompris_kwh')|float(0))|round(2) }}

{{
  (
    states('sensor.gangen_varmeovn_cal_energy_hourly') | float(0) *
    states('sensor.strompris_kwh') | float(0)
  )  | round(2)
}}

Each sensor is converted to a float then multiplied together, then the result, contained in the outermost brackets, is rounded.

In your second post above (#36), you were missing those outermost brackets, so the round was only applied to the price sensor.

1 Like

So after giving up on this, I thought I’d have another go. Wrote some errors in to see what the issue is.

What state do I still get? “unknown”

So painful. Any clues?

template:
  - sensor:
      name: test
      device_class: timestamp
      state: >
        {% set datetime_attr = state_attr('input_datetime.time', 'timestamp') %}
        {% if datetime_attr is defined %}
          {% set timestamp = datetime_attr | float %}
          {% if timestamp %}
            {% set formatted_time = timestamp | timestamp_custom('%H:%M', False) %}
            {{ formatted_time }}
          {% else %}
            {{ 'Error: Invalid timestamp' }}
          {% endif %}
        {% else %}
          {{ 'Error: input_datetime.time not defined' }}
        {% endif %}

Edit.

I thought I’d rewrite this using strftime instead. Results? “unknown”

template:
  - sensor:
      name: test
      device_class: timestamp
      state: "{{ state_attr('input_datetime.time', 'timestamp') | float | timestamp | strftime('%H:%M') }}"

What is your goal with this? Both template sensors have errors, but they are also pointless because you’re using a datetime entity which already mirrors a timestamp sensor in regards to automations.

Because this blueprint only allows sensor inputs for alarm time. The other option is a manual time which means editing the automation every day.

Ok,

{{ today_at(states('input_datetime.time')) }}

Thank you! I now get a result that isn’t “unknown”.

Should today_at use my system time or local time? It’s showing an hour earlier than the input which would be GMT. I’m in London and we’re now at BST, one hour ahead.

My system is set to London and it shows the correct current time.

I’ve tried adding local and as_local but neither resolve it.

today_at does use local time. If you’re timestamp isn’t showing up correctly then you aren’t using the correct time somewhere on your system. There were bugs in older versions of home assistant related to today_at, but they were fixed. So make sure you’re on the latest HA.

It does indeed display correctly in anything UI:

But when you check what it’s showing in the backend, via Developer / States it’s wrong: