Date formatting

I tried this and I’m getting the following error:

ERROR (MainThread) [homeassistant.helpers.entity] Update for sensor.kitchen_motion_last_updated fails
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 221, in async_update_ha_state
    await self.async_device_update()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 347, in async_device_update
    await self.async_update()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/sensor/template.py", line 196, in async_update
    self._state = self._template.async_render()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/template.py", line 138, in async_render
    return self._compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.6/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "
TypeError: can only concatenate list (not "str") to list

put this in the template editor and tell me the output

state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated')
  - platform: template
    sensors:
      kitchen_motion_last_updated:
        friendly_name: Last Kitchen Motion
        value_template: >
          {% set t = state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated') %}

And output is Unknown

no… the template editor. It’s in the UI

Sorry my bad, Output is [‘2019-01-29’, ‘14:47:28’]

change

{%- set t_string = state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated') %}

to

{%- set t_string = ''.join(state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated')) %}

so…

sensor:
  - platform: template
    sensors:
      kitchen_motion_last_updated:
        friendly_name: Last Kitchen Motion
        entity_id: sun.sun
        value_template: >
          {%- set t_string = ''.join(state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated')) %}
          {% if t_string != None %}
            {%- set t = strptime(t_string+"-+0000", "%Y-%m-%d,%H:%M:%S-%z") %}
            {%- set t = as_timestamp(t) %}
            {%- set n = now().timestamp() %}
            {%- set d = n-t %}
            {%- set midnight_today = as_timestamp(strptime(now().date() | string, "%Y-%m-%d")) %}
            {%- set midnight_yesterday = midnight_today - 86400 %}
            {%- if d < 60 %}
              Less then a min. ago
            {%- elif d < 3600 %}
              {{ (d // 60) | int }} min. ago
            {%- elif d < n-midnight_today %}
              Today at {{ t | timestamp_custom('%H:%M') }}
            {%- elif d < n-midnight_yesterday %}
              Yesterday at {{ t | timestamp_custom('%H:%M') }}
            {%- else %}
              {{ t | timestamp_custom('%m/%d at %H:%M') }}
            {%- endif %}
          {% else %}
            unknown
          {% endif %}
Update for sensor.kitchen_motion_last_updated fails
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 221, in async_update_ha_state
    await self.async_device_update()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 347, in async_device_update
    await self.async_update()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/sensor/template.py", line 196, in async_update
    self._state = self._template.async_render()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/template.py", line 138, in async_render
    return self._compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.6/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'

what does this return

{{ ''.join(state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated')) }}

Returns: 2019-01-2915:16:55

Without the space in between the time and date.

bah, do this

{{ ','.join(state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated')) }}

and this

sensor:
  - platform: template
    sensors:
      kitchen_motion_last_updated:
        friendly_name: Last Kitchen Motion
        entity_id: sun.sun
        value_template: >
          {%- set t_string = ','.join(state_attr('binary_sensor.kitchen_motion_motion_sensor','last_updated')) %}
          {%- if t_string != None %}
            {%- set t = strptime(t_string+"-+0000", "%Y-%m-%d,%H:%M:%S-%z") %}
            {%- set t = as_timestamp(t) %}
            {%- set n = now().timestamp() %}
            {%- set d = n-t %}
            {%- set midnight_today = as_timestamp(strptime(now().date() | string, "%Y-%m-%d")) %}
            {%- set midnight_yesterday = midnight_today - 86400 %}
            {%- set midnight_week_ago = midnight_today - 604800 %}
            {%- if d < 60 %}
              Less then a min. ago
            {%- elif d < 3600 %}
              {{ (d // 60) | int }} min. ago
            {%- elif d < n-midnight_today %}
              Today at {{ t | timestamp_custom('%H:%M') }}
            {%- elif d < n-midnight_yesterday %}
              Yesterday at {{ t | timestamp_custom('%H:%M') }}
            {%- elif d < n-midnight_week_ago %}
              {{ t | timestamp_custom('%A at %H:%M') }}
            {%- else %}
              {{ t | timestamp_custom('%m/%d at %H:%M') }}
            {%- endif %}
          {% else %}
            unknown
          {% endif %}
6 Likes

Now it’s working :smiley:
Amazing, thanks a million!

Going to try the other sensors now too.

Update - They work great too!

Thanks @petro I’m going to use that template…

1 Like

With the change for a required entity in templates, what should the entity be for these sensors?

They show up correctly on the front-end, but HA is trowing errors about “has no entity ids configured to track nor were we able to extract the entities to track from the value template(s)”.

You can put in any entity_id that updates more often than what you want to show.

so in the cases above you could use sensor.date as it updates every day or even sensor.time since it updates every minute.

@finity Thanks for the response, I ended up using “sensor.date”, all good now.

I’ve just come across this and thought I’d add what I use. It is just a variation on the theme but it might be interesting to someone. Also I suspect an even better solution could be arrived at by combining (some of) this with (some of) @petro’s version.

I use mine with device_trackers to report a persons current address and how long they have been there for.

{% set since_day = as_timestamp(state_attr('device_tracker.life360_person1', 'at_loc_since')) | timestamp_custom('%d') | int %}

{% set since_day_name = (as_timestamp(state_attr('device_tracker.life360_person1', 'at_loc_since')) | timestamp_custom('%A')) %}

{% if since_day == now().day %}
  {% set since_day = '' %}
{% elif since_day == now().day - 1 %}
  {% set since_day = ' yesterday' %}
{% elif since_day < (now().day - 6) and since_day > (now().day - 14) %}
  {% set since_day = ' last ' + since_day_name %}
{% elif since_day <= (now().day - 14) %}
  {% set since_day = ' on ' + as_timestamp(state_attr('device_tracker.life360_person1', 'at_loc_since')) | timestamp_custom('%d %b') %}
{% else %}
  {% set since_day = ' ' + since_day_name %}
{% endif %}

{% set since_time = as_timestamp(state_attr('device_tracker.life360_person1', 'at_loc_since')) | timestamp_custom('%H:%M') %}
                  
{% set composite_state = states('device_tracker.person1_composite') | title %}
{% if composite_state in ['Home', 'Zone2', 'Zone3'] %}
  Person1 has been at {{ composite_state }} since {{ since_time }}{{ since_day }}
{% else %}
  {% set address = state_attr('device_tracker.google_maps_xxxx', 'address') %}
  Person1 has been at {{ address }} since {{ since_time }}{{ since_day }}
{% endif %}

Results in things like;

Person1 has been at 23, My Street, My Town, MyCity a12 3bc, UK since 09:43
Person1 has been at Home since 17:41 yesterday
Person1 has been at Zone2 since last Friday

1 Like

@petro
thanks petro, i had a problem in my code which is " timer is not working at the date time i put"

here is the code:
configuration:

  • platform: template # determine if today is selected as a watering day for program 1
    sensors:
    program1_watering_day:
    entity_id: input_boolean.program1_monday, input_boolean.program1_tuesday, input_boolean.program1_wednesday, input_boolean.program1_thursday, input_boolean.program1_friday, input_boolean.program1_saturday, input_boolean.program1_sunday
    value_template: >
    {% set sensor_names = [“monday”, “tuesday”, “wednesday”,“thursday”,“friday”,“saturday”,“sunday”] %}
    {% set today_name = sensor_names[now().weekday()] %}
    {% set entity_id = ‘input_boolean.program1_’+today_name %}
    {{ is_state(entity_id, ‘on’) }}

automation:

  • alias: Reticulation Run Program 1 # start program 1 at designated time if it is enabled and today is selected as a watering day
    initial_state: ‘on’
    trigger:
    • platform: template
      value_template: >
      {{ now().strftime(’%d %H:%M:00’) == states(‘input_datetime.program1_start_time’) }}
      condition:
      condition: and
      conditions:
      • condition: state
        entity_id: input_boolean.program1_enable
        state: ‘on’
      • condition: state
        entity_id: sensor.program1_watering_day
        state: ‘true’
        action:
    • service: script.turn_on
      entity_id: script.program1_run

script:
program1_run: #run retic program 1 through each station for selected time
alias: Program 1 Run
sequence:
- service: switch.turn_on
data:
entity_id: switch.station_1_valve
- delay: “00:{{ states(‘input_number.program1_station1_run_time’)|int }}:00”
- service: switch.turn_off
data:
entity_id: switch.station_1_valve
- service: switch.turn_on
data:
entity_id: switch.station_2_valve
- delay: “00:{{ states(‘input_number.retic_program1_station2_run_time’)|int }}:00”
- service: switch.turn_off
data:
entity_id: switch.station_2_valve

You’ll have to format that properly. Edit, highlight, and press the code format button.

could you help me in that problem, I think the template got a problem

Read my last post. You need to format it properly for me to see the problems. I can’t read the code if the code isn’t formatted. Take a look at your post, notice bullets and odd spacing? That’s because you didn’t format the post.