Is 'as_timestamp(now())' misbehaving since v115? [Solved]

I use the below code for displaying a formatted time, but since 115 it only updates during HA start-up:

  - platform: template
    sensors:
      simple_time:
        friendly_name: "Simple Time"
        entity_id: sensor.time
        value_template: "{{ as_timestamp(now()) | timestamp_custom('%-I.%M %p') }}"

Is this a bug, or has something changed and I’ve missed it in the release notes?

I’ve noticed two other posts about unusual behaviour with 115, and they both involve as_timestamp(now()):

In 0.115, templates in the Template integration are evaluated more efficiently. However, the new technique has deprecated the use of the entity_id option.

That means the entity_id option in your Template Sensor is now ignored (so sensor.time is not being included). Your template contains no entities (so no listeners can be assigned) therefore it is evaluated at startup and never again (until the next restart).

For more information: Heads up! Upcoming breaking change in the Template integration

I suggest you change the template to this:

  - platform: template
    sensors:
      simple_time:
        friendly_name: "Simple Time"
        value_template: >
          {{ as_local(states.sensor.time.last_updated).timestamp() | timestamp_custom('%-I.%M %p') }}

If you test this new template in the Template Editor, it confirms that it has detected the sensor.time entity and assigned a listener to it.

The reason why that works is because sensor.time has been included in the template (it also works with all versions of Home Assistant prior to 0.115). Here’s another way to include sensor.time:

  - platform: template
    sensors:
      simple_time:
        friendly_name: "Simple Time"
        value_template: >
          {% set x = states('sensor.time') %}
          {{ now().timestamp() | timestamp_custom('%-I.%M %p') }}


EDIT

Correction. Used the wrong character (<) for indicating line-continuation!

1 Like

You’re a Superstar!!!

Thanks a million for the detailed explanation, and working code :smile:

It looks like the new system doesn’t need the < anymore, it was displaying in the UI.

So this variant does the trick:

    value_template: "{{ as_local(states.sensor.time.last_updated).timestamp() | timestamp_custom('%-I.%M %p') }}"

Actually, that was my mistake (and I’ve corrected the example). Call it a brain-fart but I used the wrong character to indicate line-continuation.

The greater-than symbol is still used to indicate that the template starts on the following line. The reason I used it is for consistency; both examples employ it and the second one becomes messier if one attempts to represent it all on one line.

If the template consists of one (short) line then, yes, you can dispense with the > and simply put the template on the same line as value_template (remembering to delimit the template with quotes).

1 Like