Extracting states from sensor - templating states

Hi

I have a sensor which is presenting states exactly like this:
[‘i morgen mandag 22. februar’, ‘onsdag 24. februar’, ‘fredag 26. februar’, ‘tirsdag 2. mars’, ‘torsdag 4. mars’]

I’m breaking these out into different sensors like this:

  - platform: template
    sensors:
      posten_next_delivery:
        friendly_name: 'Next Mail Delivery'
        value_template: >
          {{ states('sensor.postendeliverydays').split(',')[0] }}
      posten_second_delivery:
        friendly_name: 'Second Mail Delivery'
        value_template: >
          {{ states('sensor.postendeliverydays').split(',')[1] }}
      posten_third_delivery:
        friendly_name: 'Third Mail Delivery'
        value_template: >
          {{ states('sensor.postendeliverydays').split(',')[2] }}

etc.

The sensors are created and the first sensor is given a state: [‘i morgen mandag 22. februar’

I would like to have it presented as a timestamp only - without the quotes and the [ .
I have changed the device_class to timestamp, but then its presented like mandag 22. februar 2001 ?

Any ideas on how to fix this?

{{ states('sensor.postendeliverydays').split(',')[0].replace("[", "").replace("'", "") }}
1 Like

Thanks man :slight_smile:

Now is there anyway to get rid of “i morgen” or just have the state presented as a timestamp for the correct year?

EDIT: Modified your suggestion VDRainer and added some .replace

{{ states('sensor.postendeliverydays').split(',')[0].replace("i morgen", "Tomorrow").replace("[", "").replace("'", "") }}

Happy for now !

That sensor’s state value is in the format of a list:

['i morgen mandag 22. februar', 'onsdag 24. februar', 'fredag 26. februar', 'tirsdag 2. mars', 'torsdag 4. mars']

However, an entity’s state value is always stored as a string so we lose all the advantages of having a list (like accessing any item in the list by its index). The consequence is we have to resort to string parsing.

For example, the following template:

Tomorrow {{states('sensor.postendeliverydays').split(',')[0][11:-1]}}

Extracts:

mandag 22. februar

and display it as

Tomorrow mandag 22. februar

How it works

This converts the string to a list and gets the zeroth item:

split(',')[0]

This slices off the first eleven characters and the last character:

[11:-1]

What it is doing is extracting:

mandag 22. februar

from:

['i morgen mandag 22. februar'

1 Like

The possibilities are endless :slight_smile: Thanks.

Where can i read up on the topic? As my knowlegde to all the Home Assistant stuff grows, so does the challenges…at the same pace my config and ui is developing :grin: