@basvankuijck wrote:
I currently have this sensor:
--- platform: template sensors: garbage_paper: friendly_name: 'Papier' entity_id: sensor.time, sensor.afval value_template: >- {% set date = strptime(state_attr('sensor.afval', 'paper'), '%Y-%m-%dT%H:%M:%S%z') %} {% set diff = as_timestamp(date) - as_timestamp(strptime(states.sensor.date_time.state, "%Y-%m-%d, %H:%M")) %} {% set days = diff | timestamp_custom("%j") | int %} {% set hours = (diff / 3600) | int %} {% if days == 1 %}Morgen{% elif days == 2 %}Overmorgen{% elif days > 0 %}Over {{ days }} dagen{% elif hours > 0 %}Over {{ hours }} uur{% else %}Zometeen{% endif %} garbage_organic: friendly_name: 'GFT' entity_id: sensor.time, sensor.afval value_template: >- {% set date = strptime(state_attr('sensor.afval', 'organic'), '%Y-%m-%dT%H:%M:%S%z') %} {% set diff = as_timestamp(date) - as_timestamp(strptime(states.sensor.date_time.state, "%Y-%m-%d, %H:%M")) %} {% set days = diff | timestamp_custom("%j") | int %} {% set hours = (diff / 3600) | int %} {% if days == 1 %}Morgen{% elif days == 2 %}Overmorgen{% elif days > 0 %}Over {{ days }} dagen{% elif hours > 0 %}Over {{ hours }} uur{% else %}Zometeen{% endif %} garbage_other: friendly_name: 'Rest + Plastic' entity_id: sensor.time, sensor.afval value_template: >- {% set date = strptime(state_attr('sensor.afval', 'other'), '%Y-%m-%dT%H:%M:%S%z') %} {% set diff = as_timestamp(date) - as_timestamp(strptime(states.sensor.date_time.state, "%Y-%m-%d, %H:%M")) %} {% set days = diff | timestamp_custom("%j") | int %} {% set hours = (diff / 3600) | int %} {% if days == 1 %}Morgen{% elif days == 2 %}Overmorgen{% elif days > 0 %}Over {{ days }} dagen{% elif hours > 0 %}Over {{ hours }} uur{% else %}Zometeen{% endif %}
Which parses pickup dates for my garbage bins into readable date formats (in Dutch).
As you can see the
value_template
for each sensor is almost identical (apart from the attribute definition; paper, organic, other). It all works well, but I’m not happy with the duplication of the ‘code’.Isn’t there a way this can be improved so I can only have one place that handles the parsing of these dates.
Maybe in the lovelace card itself? Any ideas are welcome.
Posts: 3
Participants: 2