How to convert time format to float?

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

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 }}

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?

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 }}

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}}

ah…details…details…

1 Like

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 }}

And we can use template helpers nowadays:

Just Replace ‘10h 30m’ by states(‘sensor.the_other_sensor’)

Thanks a lot Tom.
Apologies for the confusion
It works

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 :stuck_out_tongue:

1 Like