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?
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:
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. 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.