Comparison between two hours

Hallo,
How can I compare if the local time is between two hours?
image

Convert the 2 times into a single unit and then compare the current time (also as the single unit) to them. This has to be done using templates. The templates will be different depending on where you want to use this comparison.

You don’t say, but assuming those two are input_datetime’s with just time, then you could do something like this:

{% set t = now().time() %}
{% set t = (t.hour*60+t.minute)*60+t.second %}
{% set start = state_attr('input_datetime.start_time', 'timestamp') %}
{% set stop = state_attr('input_datetime.stop_time', 'timestamp') %}
{% if start < stop %}
  {{ start < t < stop }}
{% else %}
  {{ t > start or t < stop }}
{% endif %}

I’ve recently been doing something like this. I got it working but I am pretty sure that there nust be a better way. I must say I do find working with dates and times in templates a bit of a struggle!!

I have an input_datetime representing the start and an input_number representing the duration.

When HA starts I need to check if ‘now’ is between ‘start time’ and ‘start time plus duration’ and if it is set a timer for whatever time is remaining. As I said, this works but I’d love to see it done more elegantly…

      - condition: template
        value_template: >
          {% set time_now = as_timestamp(now()) %}
          {% set start_time = states('input_datetime.guest_mode_schedule_1_start_time') %}
          {% set start_time = as_timestamp(now()) | timestamp_custom('%Y-%m-%d') + ' ' + start_time %}
          {% set duration = states('input_number.guest_mode_schedule_1_duration') | int * 60 %}
          {% set end_time = as_timestamp(start_time) + duration %}

          {{ time_now > as_timestamp(start_time) and time_now < end_time }}
    action:
      - service: timer.start
        data_template:
          entity_id: timer.guest_mode_schedule_1_duration
          duration: >
            {% set time_now = as_timestamp(now()) %}
            {% set start_time = states('input_datetime.guest_mode_schedule_1_start_time') %}
            {% set start_time = as_timestamp(now()) | timestamp_custom('%Y-%m-%d') + ' ' + start_time %}
            {% set duration = states('input_number.guest_mode_schedule_1_duration') | int * 60 %}
            {% set end_time = as_timestamp(start_time) + duration %}
            {% set seconds_left = end_time - time_now %}
            {% set hours_left = seconds_left // 3600  %}
            {% set minutes_left = (seconds_left - (hours_left * 3600)) // 60 %}

            {{ '%02i' | format(hours_left) }}:{{ '%02i' | format(minutes_left) }}:01