Formatting template sensor state last changed


I’m stuck with formatting sensor state last_changed.

The state of the sensor is set through the HA API:
curl -X POST -H "Content-Type: application/json" -d "{\"state\": \"NEW STATE\"}" http://HA_IP:8123/api/states/sensor.ispymotion_gate

The state is properly set, it returns:
{“attributes”: {}, “entity_id”: “sensor.ispymotion_gate”, “last_changed”: “2017-02-25T22:02:37.528269+00:00”, “last_updated”: “2017-02-25T22:02:37.528269+00:00”, “state”: “NEW STATE”}

The aim is to get “last_changed” printed out and formatted on the state card below the state of the sensor. I was experimenting on the dev template with strptime but did not succeed.

value_template: "{{ states.sensor.ispymotion_gate.last_changed }}" returns:
value_template: "2017-02-25 22:02:37.528269+00:00"

The format I want to achieve is “2017-02-05 22:02:37”

value_template: "{{ strptime(value_json.states.sensor.ispymotion_gate.last_changed, '%Y%m%d').date() }}" returns: Error rendering template: UndefinedError: ‘value_json’ is undefined

Any suggestions how to make it work?


I’ve just managed to do it. I had to use strftime
value_template: "{{ states.sensor.ispymotion_gate.last_changed.strftime('%Y.%m.%d %H:%M:%S') }}"



Thanks for posting the solution! Always appriciated!


no problem!

Just ran into a new quest:)
How to determine the days between the date above, and now()?

It’s rather easy using the date object.

{{ now().date().day - }}


Yeah, I’ve figured it out too:
'{{now() - states.sensor.ispymotion_gate.last_changed}}'

The only problem is, that it won’t update for some reason.
On the dev tool it does for sure, but if I put it into the configuration.yaml it won’t.

I’ve found a way, but I’m not sure if it’s a soltion or a workaround.

I’ve created a simple time sensor template with the value now() . It updates every 30 secs or so. Then used this sensor’s last_updated value to do the math:

{{ states.sensor.mytime.last_updated - states.sensor.ispymotion_gate.last_changed }}