Using now() versus sensor.time

I’m going through some of my code trying to rationalise some of my date and time usage.

Is there any reason to prefer now() over sensor.time. My gut says that now() is always better because it is baked into Python whereas sensor.time is, well, a sensor which relies on HA. Is that reasonable?

Specifically, for example is,

value_template: "{{ now().hour ~ ':' ~ now().minute == states('input_datetime.my_time') }}"

better than

value_template: "{{ states('sensor.time') + ':00' == states('input_datetime.my_time') }}"

and

value_template: "{{ states('sensor.time') == (state_attr('input_datetime.my_time', 'timestamp')) | timestamp_custom('%H:%M', false) }}"

Or doesn’t it matter, or is there an even better way to do this?

It depends on where and how you’re using it.

In general now() is more versatile, but sensor.time is an entity so will cause state changes. So, e.g., if the template is in a template trigger, a template sensor or a wait_template, then sensor.time has the added benefit of automatically getting the template to be evaluated when it changes (which it does once a minute.) But in a condition, that’s not an issue.

now() returns a Python datetime, so, like I said, that makes it much more versatile. But again, it really depends on how you’re using it.

One thing I will suggest, though, about using now() – in a given template only evaluate it once. In your example:

value_template: "{{ now().hour ~ ':' ~ now().minute == states('input_datetime.my_time') }}"

It gets evaluated twice. What happens if the first one evaluates just before an hour change, and the second one evaluates right after an hour change? It only takes a microsecond or two. And I’ll say again, if it can happen, it will happen. :slight_smile: So I’d change it to:

value_template: >
  {% set n = now() %}
  {{ n.hour ~ ':' ~ n.minute == states('input_datetime.my_time') }}

BTW, not sure that would work anyway, because if n.hour is less than 12, or n.minute is less than 10, I don’t think you’ll get what you want.

1 Like

What an excellent point!

And in fact that might be explaining some rare but unexpected behaviour I’ve been experiencing! (I need to look into this to confirm).

As you said…

:slight_smile:

1 Like