Jinja2 tempating: Limit time scope in an if-statement

I would really appreciate som help with Jinja2 templating

I want an if-statement that is “Good” at 05:40 or later.

    {% if (now().hour >= 5 and now().minute >= 40 ) %}
       Good
    {% else %}  
       Bad
    {% endif %} 

Obviously the example above does only work when the hour is 5 or greater AND when the minutes are 40 or greater. At, let’s say 7:25, I will receive a “Bad” result.

Any ideas of how I can make this simple example work so it will return “Good” every day at 05:40 or later?

It does not have to be an if-statement, any solution will do.

Convert everything to 1 unit and evaluate. EDIT, this is converted to minutes.

{% set t = now().hour * 60 + now().minute %}
{% set time_limit = 5 * 60 + 40 %}
{% if t >= time_limit %}
   Good
{% else %}  
   Bad
{% endif %}

Or may be add another condition…
(Sorry cant format properly on mobile)

     {% if (now().hour >= 5 and (if (now().hour == 5 and now().minute >= 40) or (now().hour > 5 and now().minute >=0) ) 
        %} 

        Good {% else %} 

        Bad {% endif %}

Thanks @petro and @dearlk. Both your solutions looks interesting and that gave me an idea.

Is it possible to get the amount of time that have passed since midnight In seconds?
If so, then it would be an easy thing to to something like

(5 hours and 40 minutes = 20400 seconds)

{% if time_since_midnight >= 20400  %} 
Good 
{% else %} 
Bad 
{% endif %}

The question at hand is: How do I create that variable time_since_midnight and populate it with the correct amount of seconds?

This would do the job although the code would not be so easy to read as in my fist attempt.

it is, but it’s more work then what you expect.

{% set t = now().hour * 3600 + now().minute* 60 + now().second %}
{% if t >= 20400 %}
   Good
{% else %}  
   Bad
{% endif %}

How about this:

    {% set nw = now() %}
    {% if nw.hour >= 5 and nw.minute >= 40 or nw.hour >= 6 %}
       Good
    {% else %}
       Bad
    {% endif %}

FWIW, I include the first statement so that all of the comparisons use the exact same time. It also makes the expression slightly more compact. Not sure if this is necessary.

And, BTW, you can also do this:

    {% set nw = now() %}
    {{ 'Good' if nw.hour >= 5 and nw.minute >= 40 or nw.hour >= 6 else 'Bad' }}

That was some interesting code.
I’ll try them all out and see what will fit my project.

Question: What is the scope of that variable? Just this script/automation/template or can I use the variable in my entire configuration?

Just that template.

1 Like