Subtract one sensor value from another sensor value

Hello,
how can I subtract one sensor value from another sensor value using template sensor?
This doesn’t work:
value_template: "{{ as_timestamp(states.sensor.nextsunset) - as_timestamp(states.sensor.nextsunrise)}}"

Thank you.

Do you have sensors set up for nextsunset and next sunrise already or are you trying to pull out the attributes of the sun sensor?

Hello,
yes, I have sunset and sunrise sensors already set up as a template sensors and they are working fine.

try

value_template: “{{ states(sensor.nextsunset)|float - states(sensor.nextsunrise)|float }}”

I’ve got this error: :thinking:
UndefinedError: 'sensor' is undefined

have you updated to 0.81.0? Can you show me what your states look like for this sensor

Yes, I am on 0.81.0.

- platform: template
    sensors: 
      nextsunset:
        entity_id: sun.sun
        value_template: "{{ as_timestamp(states.sun.sun.attributes.next_setting) | timestamp_custom('%-H:%M') }}"

Close, but you need to put the sensor in single quotes:

value_template: “{{ states(‘sensor.nextsunset’) | float - states( ‘sensor.nextsunrise’) | float }}

No error, but result is 0.0. My sensors are times… how can I subtract times?

Thank you.

So this one is working, but result is off by one hour. 16:33 - 6:28 should be 10:05 but it is 11:05

value_template: "{{ ((as_timestamp(states.sun.sun.attributes.next_setting)) - (as_timestamp(states.sun.sun.attributes.next_rising))) | timestamp_custom('%H:%M') }}"

Any idea why? What am I missing?
Thanks.

please, can you help me in this?