Hi
I am getting some strange behaviour back from a template sensor that I created. The entity’s state returns a string that includes a time of day in 24hr format. I wanted it in AM/PM format. I am clearly doing something wrong because when my templated attempt returns a value, the time is different to the original value. 5 minutes different. Can anyone spot what I am doing wrong. Or suggest a more elegant way to do this.
The original entity returns something like this: Low tide at 20:06
The below code does what I wanted it to but why the hec are the times different?
sensors:
mycity_tides_custom:
value_template: >
{{ states('sensor.mycity_tides').split(" at ")[0] }} at {{ as_timestamp(strptime(states('sensor.mycity_tides').split(" at ")[1], '%H:%M')) | timestamp_custom("%I:%M %p") }}
and got 08:05:00 PM. I added the seconds display to eliminate rounding or leap seconds. Mine is exactly a minute out. But adding a recent date to the timestamp to prevent it thinking it’s 1900:
It gets even more weird, when I do in dev tools => template
{% set foo = "Low tide at 20:06" %}
{{ foo.split(" at ")[0] }} at {{ as_timestamp(strptime(foo.split(" at ")[1], '%H:%M')) | timestamp_custom("%I:%M %p") }}
I only get
OverflowError: timestamp out of range for platform time_t
But this does work for me:
{% set foo = "Low tide at 20:06" %}
{% set split = foo.split(" at ") %}
{{ now().time().fromisoformat(split[1]).strftime("%I:%M %p") }}
Also, you might want to add a case for when the string isn’t as expected (or unknown) to not throw errors then.
Your call. My solution of adding a date and @septillion’s fromisoformat both do the trick. Mark whichever one you actually use as the solution — I don’t think the “loser” will be too upset .
Yes I am (RPi4 when x64 was still experimental). And ahh, somehow strptime thinks it’s a good idea to place the time in 1900, doh. I assumed it would place it in 1970…