When the 196 hrs changes to 99 hrs the {{ states('sensor.my_date')[:3] }} it will return "99 ", as there are only two digits. Same problem when it reaches 9.
Is there a way to extract the number up to the first “space”?
Is there something similar to deal with the varying lengths, as per my 196 to 99 hours problem above?
I don’t think there are leading spaces there but just extracting up to the first space would solve the problem.
If the string always contains hrs or you can use it as a delimiter in split(). The result will be a list containing two items, 99 and 10/06/2024 , that can be referenced by list index.
Try this in the Template Editor:
{% set x = states('sensor.my_date').split(' hrs or ') %}
{{ x[0] }}
{{ x[1] | trim }}
Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title signaling to other users that this topic has been resolved. This helps users find answers to similar questions.
I cant get this to works, i want to calculate how many days my HA-server has been running, using system monitor sensor value.
I have set up helper with this.
It returns 0, tried trimming but didnt work, when I replace states(‘sensor…’) with date like 10/05/2024, it gives me days in negative, i would like to get days in positive, but didnt figure it out.
I tried to change that order, but i didnt get any results, it allways reported Unknown.
That sensor gives May 22, 2024 at 20:33
Found other way, it worked. But i have read to not use as_timestamp(now() and it should be replaced by Time&Date, but didnt get that to work either, is my date formating wrong, tried time_date and date_time?
{{ (((as_timestamp(now()) - as_timestamp(states('sensor.system_monitor_viimeinen_kaynnistys')))) | int /60/1440) | round(0) }}
I believe they are miss understanding the advice. The advice is most likely referencing datetime objects over the use of as_timestamp, which is suggested because datetime objects handle timezones better than as_timestamp.
He’s claiming that as_timestamp is working unless I miss read something. Both as_timestamp and as_datetime use the same underlying code to determine the date from an iso (or some non-iso) formats.
If his format is truly May 22, 2024 at 20:33, then he will need to use strptime like you say.
{{ now() - strptime("May 22, 2024 at 20:33", "%B %d, %Y at %H:%M")|as_local}}
in his case
{{ (now() - strptime(states('sensor.system_monitor_viimeinen_kaynnistys'), "%B %d, %Y at %H:%M")|as_local).days }}
I had the impression that the advice was about using Time&Date sensors instead of now() which would have been applicable a long, long time ago when now() didn’t serve to periodically update a template.