Issue with template - no default was specified

Hi, I have this template and it’s ok but if the sensor is unavailable, I get error. Where should I put default 0 or 01/01/2023 12:12:12?

{{states.binary_sensor.kitchen_window_opening.last_updated | as_timestamp|timestamp_custom('%d/%m/%Y %H:%M:%S')}}
  • TemplateError(‘ValueError: Template error: as_timestamp got invalid input ‘’ when rendering template ‘{{states.binary_sensor.kitchen_window_opening.last_updated | as_timestamp|timestamp_custom(’%d/%m/%Y %H:%M:%S’)}}’ but no default was specified’) while processing template ‘Template<template=({{states.binary_sensor.kitchen_window_opening.last_updated | as_timestamp|timestamp_custom(’%d/%m/%Y %H:%M:%S’)}}) renders=4>’ for attribute ‘_attr_native_value’ in entity ‘sensor.kitchen_window_sensor_last_updated’

Your initial sensor might not be ready to be parsed. You need default values for these cases;

Template with an invalid entity renders 01/01/1970 01:00:00
{{ state_attr('sensor.water_pump_energy_costx','last_reset') | as_timestamp(0) | timestamp_custom('%d/%m/%Y %H:%M:%S') }}

Template with a valid entity renders 04/10/2023 22:51:43
{{ state_attr('sensor.water_pump_energy_cost','last_reset') | as_timestamp(0) | timestamp_custom('%d/%m/%Y %H:%M:%S') }}

Also, check this - Templating - Home Assistant

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)
1 Like

Perfect, working template is

{{states('binary_sensor.kitchen_window_opening.last_updated') | as_timestamp(0)|timestamp_custom('%d/%m/%Y %H:%M:%S')}}