Comparing value to time

I would like a binary sensor to (briefly) change to ‘yes’ at the time I need to leave for work + 15 minutes.

This bit

{{ (((((states('sensor.travel_time_to_work') ) | float) +15  ) * 60 ) + as_timestamp(now())) | timestamp_custom(' %H:%M') | replace(" 0", "") }}

correctly returns my arrival time at work (with a 15 min buffer). How do I compare this to 0800hrs?

This does not work (always returns NO):

template:
  - binary_sensor:
      - name: "Need to leave home to get to work"
        state: >
         {% if  ((((((states('sensor.travel_time_to_work') ) | float) + 15  ) * 60 ) + as_timestamp(now())) | timestamp_custom(' %H:%M') | replace(" 0", ""))  == "08:00" %}
            {{'YES'}}
          {% else %}
            {{'NO'}}
          {% endif %}

Thank you!

i think i understand what you’re asking. … if so, i think this works for you. i made it a little pedantic just to be clearer what it does so you can correct me if i’m misunderstanding.

{% set travel_time = 30 %}
{% set work_start = "22:30" %}

{% set work_start_dt = as_datetime(now().date() | string + " " + work_start)%} 
{% set work_start_grace = work_start_dt + timedelta(minutes=15) %}
{% set eta = (now() + timedelta(minutes=travel_time)).replace(tzinfo=none) %}
{{ work_start_dt <= eta and eta < work_start_grace }}

nuke the first 2 lines. just there so you can pop the whole thing in dev tools->template
replace the travel_time with your “sensor.travel_time_to_work”…
and work_start with whatever time you’re supposed to be at work by.

is the same as

{% set work_start_dt = today_at(work_start) %} 

And I believe this:

{% set work_start_grace = work_start_dt + timedelta(minutes=15) %}

Should be minus timedelta. If it’s plus then he arrives late at work? Or am I reading this wrong?

And to OP. Binary sensors can’t be yes/no, they need to be on/off

2 Likes

Thank you! Perfect :slight_smile:

op said it should be “yes” for the time he’s supposed to leave for work (e.g. 7:30) plus 15 minutes (which i interprested it to be 7:45).

i figured he’s got a 15 minute grace period… which is why i called it work_start_grace.

however if the intent was the other way, then not only does work grace have to change, but the final compare does as well:

{% set travel_time = 30 %}
{% set work_start = "23:00" %}

{% set work_start_dt = today_at(work_start) %} 
{% set work_start_early = work_start_dt - timedelta(minutes=15) %}
{% set eta = (now() + timedelta(minutes=travel_time)) %}
{{ work_start_early < eta and eta < work_start_dt  }}

@Hellis81 what i had isn’t quite the same as today_at. it’s close, but one is relative time and one’s not. so you’d have to convert some of the other code if i use today_at()… i didn’t use it because i wasn’t familar with today_at (so thanks!!!). i converted the above to use today_at() which shrinks the code a touch.

1 Like