Get seconds from time (duration) of different input formats

Hi,

I have script with a duration field. Valis inputs for a duration are:

  • 0
  • 00:00:00
  • hours: 0
    minutes: 0
    seconds: 0

But how get that? I have split at : template to get the three parts and so I can calculate the seconds. But the duration is in the hours:, minutes:, seconds: format the split did not work.

This works with β€˜00:00:00’ but not with the other varaintes:

        {% set hrs = time.split(':')[0] | int(0) %}
        {% set mins = time.split(':')[1] | int(0) %}
        {% set secs = time.split(':')[2] | int(0) %}
        {% set duration = (hrs * 60 * 60) + (mins * 60) + secs %}

Any hint for me to handle the different input formats?

Steffen

Hey @SteffenDE,

I’m in the same situation, did you ever find a solution?

Regards,

Nicolas

No sorry, I found no solution.

1 Like

What about:

  - sensor:
      - name: Laatste irrigatie duur seconden
        unique_id: 'laatste_irrigatie_duur_seconden'
        unit_of_measurement: "sec"
        state: >
          {% set duration = states('sensor.your_timestamp_total') %}        
          {% if duration %}
            {% set parts = duration.split(':') %}
            {% set hours = parts[0] | int %}
            {% set minutes = parts[1] | int %}
            {% set seconds = parts[2] | int %}
            {% set total_seconds = hours * 3600 + minutes * 60 + seconds %}
            {{ total_seconds * 1 }}
          {% else %}
            0
          {% endif %}

Henk

@SteffenDE this will work with any duration selector.

{% if time is mapping %}
  {{ timedelta(**time).total_seconds() }}
{% elif time is string %}
  {% set h, m, s = time.split(':') | map('int', 0) | list %}
  {{ timedelta(hours=h, minutes=m, seconds=s).total_seconds() }}
{% elif time is is_number %}
  {{ time }}
{% else %}
  0
{% endif %}

@henkhoekema that’s a template entity using a duration entity, not a duration selector. However, this will work for a duration entity.

{{ (states('sensor.your_timestamp_total') | as_timedelta).total_seconds() }}