I know I am late to the party, but just wanted to put it here so anyone else struggling with this issue may find a solution.
Similar to the OP, I was trying to create sensors based on the Ping integration, which requires IP addresses to be configured (unless you mess with hosts file or DNS records, I guess) and creates sensors based on them. So, I was trying to get the last updated time and hit a wall when ı tried to get the last updated time of the sensor with numbers in the name:
updated {{ relative_time(states.sensor.ookla_speedtest_download.last_changed) }} ago
yields
updated 41 minutes ago
But
updated {{ relative_time(states.sensor.192_168_6_1_jitter.last_changed) }} ago
gives an ugly “TemplateSyntaxError: expected token ‘,’, got ‘_jitter’” error message.
After swimming through murky waters of unhelpful documentation (seriously, the authors of the documentation need to keep in mind that not everyone who deals with such systems are developers), and wasting many hours, through trial-and-error, I found out that
updated {{relative_time(states[“sensor.192_168_6_1_jitter”].last_changed)}} ago
gives me the output I needed:
updated 4 seconds ago.
Long story short, if your sensor name contains any numbers, and if there’s no simple way to change it, you need to enclose it between [" and "]
Weirdly, if you are NOT going to do any funky formatting on the result, such as trying to extract the last changed time of the sensor value
{{(states(‘sensor.192_168_6_1_jitter’))}}
also works, giving you the sensor values, like 0.249, etc. I don’t know why it works and why it does not work when some extra stuff is added, and I don’t care. All I’m saying is that the existing documentation leaves much to be desired.
Apologies if my formatting offends anyone, but this is my first post here, and I have no intention to fight with weird formatting rules anymore for the day.
Hope this helps.
EDIT:
Even more weirdly, the above working example only works in Template Editor. However, if you copy/paste it to a template sensor state field, you get “invalid template (TemplateSyntaxError: unexpected char '”’ at 23)" error message. Apparently, people who develop different parts of the software had different standards. Luckily, the solution is simple: replace " with ’ to obtain:
{{relative_time(states[‘sensor.192_168_6_1_round_trip_time_average’].last_changed)}} ago
which works.
Note to self: What seems to work in Template Editor is not guaranteed to work somewhere else.