I have tried many methods on the forum to change these times to a 12 hr format in my template.
I can change them but they do not update, or my code changes all of them to the same time.
Here is a sample of what I have tried.
it didn’t show you NY time as you used now(), it’s local time.
I think you need to keep your World Clock sensors and create some template sensors that will use their state to represent it in 12h format. Here I created 2 sensors so you get the idea and add as many as you like:
- platform: template
sensors:
simple_time_ny:
friendly_name: 'New York'
<<: &icon
icon_template: 'mdi:clock'
value_template: >
{% set time = states('sensor.new_york') %}
{% set hour = time[:2]|int %}
{{ '{:02d}:{} {}'.format(hour % 12, time[3:5], 'PM' if hour>11 else 'AM') }}
simple_time_la:
friendly_name: 'Los Angeles'
<<: *icon
value_template: >
{% set time = states('sensor.los_angeles') %}
{% set hour = time[:2]|int %}
{{ '{:02d}:{} {}'.format(hour % 12, time[3:5], 'PM' if hour>11 else 'AM') }}
You’ll need to change your Lovelace card to use these sensors:
Firstly thank you for the reply. I enabled the code and it works sort of. But not understanding your code (if you could explain please the last two lines of the value template that would help me out) I did not know how to fix it.
{% set hour = time[:2]|int %}
{{ '{:02d}:{} {}'.format(hour % 12, time[3:5], 'PM' if hour>11 else 'AM') }}
What is happening is that from 12:00 PM to 12:59 PM the display reads for 12:25 PM (00:25 PM).
As I said I do not fully understand the code.
Thank you.
carltonb
{% set hour = time[:2]|int %} assigns the first 2 characters (cast to int) of the original sensors’ state string to hour variable
the next string composes the template sensor’s state:
first field (0-padded 2 characters) will be hour in 12h format (i.e remainder of hour / 12)
second field (after colon) is 2 characters starting from #3 of your original sensor’s state string - minutes (we don’t change them)
the third field displays PM if hour > 11 and AM otherwise.
If you’re saying it doesn’t work correctly between 12:00 PM to 12:59 PM that’s correct, this should fix it:
{{ '{:02d}:{} {}'.format(hour if hour == 12 else hour % 12, time[3:5], 'PM' if hour>11 else 'AM') }}
i.e hour == 12 is a special case, we need to display the hour itself, not hour % 12 (=00).
hope it does the trick.
basically it’s Python: slicing and string formatting (+ a bit of Jinja templates)
In 0.115.x, the entity_id is not used anymore, and since the value_template has no entity to listen to, it is not updated. There is a whole topic on that change.
Thank you for the example. This will make it easy to find other places that are broken and implement a similar solution. This should be used as an example in that topic