ste.luci
(Stefano)
1
Hi
I tried to find similar questions but I wasn’t able to make it work.
Apologies if this is a duplicate topic.
I have a sensor showing the day length for a specific location.
The sensor output is something like
11h 30m
I would like to convert that value to a float so that the hour and minutes are ‘translated’ to a number.
E.g.,
8h 30m → 8.5
12h 15m → 12.25
and so on
I think I should use a template sensor, but all my tests failed.
Thank you
Stefano
aceindy
(Aceindy)
2
10.30 → 10,5
{% set time_str = "10:30" %}
{% set time_parts = time_str.split(":") %}
{% set hours = time_parts[0] | int %}
{% set minutes = time_parts[1] | int %}
{% set time_decimal = hours + (minutes / 60) %}
{{ time_decimal }}
ste.luci
(Stefano)
3
Thank you aceindy.
My format is 11h 57m (as status of sensor.day_length) so I suppose I should use
{% set time_parts = states.sensor.day_length.split("h ") %}
Is this correct?
Also, I should first get rid of the m with a replace, right?
tom_l
4
Not quite Ace.
{% set time_str = "10h 30m" %}
{% time_str|replace('h ',':')|replace('m','') %}
{% set time_parts = time_str.split(":") %}
{% set hours = time_parts[0] | int %}
{% set minutes = time_parts[1] | int %}
{% set time_decimal = hours + (minutes / 60) %}
{{ time_decimal }}
ste.luci
(Stefano)
5
Hi
I am trying the below but getting errors.
Any hint?
Thank you
- platform template:
sensors:
day_length_dec:
value_template: {% set time_str = states.sensor.the_other_sensor | replace('h ',':') | replace('m','') %}
{% set time_parts = time_str.split(":") %}
{% set hours = time_parts[0] | int %}
{% set minutes = time_parts[1] | int %}
{% set time_decimal = hours + (minutes / 60) %}
{{ time_decimal}}
tom_l
7
Try as we might we can’t mind read what those errors are. In future please post them here instead.
Anyway, try this:
value_template: >
{% set time_str = states('sensor.the_other_sensor') | replace('h ',':') | replace('m','') %}
{% set time_parts = time_str.split(":") %}
{% set hours = time_parts[0] | int %}
{% set minutes = time_parts[1] | int %}
{% set time_decimal = hours + (minutes / 60) %}
{{ time_decimal }}
aceindy
(Aceindy)
8
And we can use template helpers nowadays:
Just Replace ‘10h 30m’ by states(‘sensor.the_other_sensor’)
ste.luci
(Stefano)
9
Thanks a lot Tom.
Apologies for the confusion
It works
aceindy
(Aceindy)
10
It could even be shorthed a little:
{% set time_str =states(‘sensor.the_other_sensor’)| replace('h ',':') | replace('m','') %}
{% set time_parts = time_str.split(":") %}
{{ time_parts[0] | int + ( time_parts[1] | int / 60) }}
But that is just cosmental
1 Like