Message append time now()

data_template:
message: ‘{%- if is_state(“binary_sensor.door”,“on”)-%}
Front Door Open
{%- else -%}
Front Door Closed
{%- endif -%}

it works perfect
want to add time to message (sent on telegram)
{{now().hour ~ now().strftime(’:%M’)}

Always gives me error

Help?

I think you are just missing the last curly brace.
this works for me:

{{now().hour ~ now().strftime(':%M')}}

How about:

{{ now().timestamp()|timestamp_custom('%H:%M') }}

Or even:

{{now().strftime('%H:%M')}}

Yeah forgot the bracket when pasted code… but that was not the problem.

So how do you merge that in the above function after closee or open text?

data_template:
  message: "Front Door {{ 'Open' if is_state('binary_sensor.door', 'on') else 'Closed' }} at {{ now().strftime('%H:%M') }}"

Or, if you’d rather not have one big line:

data_template:
  message: >
    Front Door {% if is_state('binary_sensor.door', 'on') -%}
      Open
    {%- else -%}
      Closed
    {%- endif %} at {{ now().strftime('%H:%M') }}

Perfect. Thank you. It works.

Now I need to find a way to add a space before at

Now, I know quite a few programming languages… but this one I seem to have some trouble to get it.
Is there a manual, online reference, etc… I could use?

Can you post what you have now? The solutions I provided both have a space before at.

        {%- if is_state("binary_sensor.door","on")-%}
        Front Door Open
        {%- else -%}
        Front Door Closed
        {%- endif -%} at {{ now().strftime('%H:%M') }}

what I get as message is: Closedat hh.mm

That’s because you specified too many dash characters in your jinja statements. The dash character means strip all whitespace in that direction. I very carefully constructed this accordingly:

    Front Door {% if is_state('binary_sensor.door', 'on') -%}
      Open
    {%- else -%}
      Closed
    {%- endif %} at {{ now().strftime('%H:%M') }}

Notice how there is no dash at the end of {%- endif %}? Also there’s no dash at the beginning of {% if is_state('binary_sensor.door', 'on') -%} for the same reason.

If you want to just fix what you have, then I’d suggest:

        {% if is_state("binary_sensor.door","on") %}
        Front Door Open
        {%- else %}
        Front Door Closed
        {%- endif %} at {{ now().strftime('%H:%M') }}

This strips whitespace (including end of lines) after “Front Door Open” and “Front Door Closed”, but no other whitespace is stripped (except for everything before the first non-whitespace character, which is stripped automatically.)

Awesome.
I missed completely that detail.

I did program with Python before… but never this “script” language… :S

Thanks @pnbruckner

Same here. But I figured this out from other posts, as well as reading:

http://jinja.pocoo.org/docs/dev/templates/#whitespace-control

1 Like