Passing last_changed delta to python_service with templates

I’m trying to pass the time since a state last changed to a python_script service using templates with the following automation:

- id: shower_timer_id
  alias: Shower Timer
  trigger:
  - entity_id: switch.master_shower_switch
    for:
      minutes: 60
    from: 'off'
    platform: state
    to: 'on'
  - entity_id: switch.master_shower_switch
    for:
      seconds: 5
    from: 'on'
    platform: state
    to: 'off'
  - entity_id: switch.master_shower_switch
    from: 'on'
    platform: state
    to: 'off'
  action:
  - data:
      entity_id: switch.master_shower_switch
      last: >
        {{ as_timestamp(now()) - as_timestamp(states.switch.master_shower_switch.last_changed) }}
    service: python_script.timed_off

And then receiving it with:

logger.debug('data.last : {}'.format(repr(data.get('last'))))

It looks like this isn’t being evaluated as a template but I’m running out of ways to format the automation that don’t generate errors when I reload the automation (even though the check errors button is returning a valid configuration):

Oct 03 03:03:13 HassPi hass[635]: 2017-10-03 03:03:13 DEBUG (Thread-4) [homeassistant.components.python_script.timed_off.py] data.last : ‘{{ as_timestamp(now()) - as_timestamp(states.switch.master_shower_switch.last_changed) }}\n’

for example:

      last: '{{ as_timestamp(now()) - as_timestamp(states.switch.master_shower_switch.last_changed) }}'

Am I missing something in my syntax to trigger the template?

Thanks,
Devan

1 Like

Figured it out, should have been using data_template instead of data in packaging the data for service call.

You must use data_template in place of data when using templates in the data section of a service call.

https://home-assistant.io/docs/automation/templating/#template