Templates, dates and times

This Pull Request shows in a clear way what happens if the documentation is not as good as it should be. In short, it’s about Templating and how people start to think about creative ways to solve it if it’s not documented. Let’s assume that we want the current year. There are a couple of options available to do that:

We want it simpler, right? Templating offers now() and utcnow(). We will stick with now() in this blog post but it applies to utcnow() as well. Our documentation said:

now() will be rendered as current time in your time zone.

Hmmm, …OK, that’s a start. How to get the year? {{ now() }} gives you 2017-10-14 20:27:23.700401+02:00 which is far more than we are looking for. As an user you don’t want to dive into the code but there would you find the solution. You will get a Python datetime object from {{ now() }}. This means that you can access more than you think in a template:

  • For the time: now().microsecond, now().second, now().minute and now().hour
  • For the date: now().day, now().month and now().year
  • Misc: now().weekday() and now().isoweekday()

For the year it would be: {{ now().year }}. I guess that there are rare use cases for now().resolution, now().min and now().max too.

Hacktoberfest is still running. Working on the documentation is pretty easy. If you know a nice trick, want to help improving the page of a platform or just fix typo then please do. Our Website/Documentation section contains some requirements which are defined in the Documentation Standards and the “Create a page” documentation for other useful details.

Thanks to Egor Tsinko for bringing this issue to our attention.

This is a companion discussion topic for the original entry at https://home-assistant.io/blog/2017/10/15/templating-date-time/

now() does not work well in templates. Fill a template sensor with the value {{ now().strftime(’%M’) }} and you’ll see it’s often a few minutes behind.

I believe this is because now() is only evaluated when a sensor state change is detected and the state is updated. If you want the state of your template sensor to be updated with the time, use “states(‘sensor.time’)” instead.

See also https://www.home-assistant.io/integrations/time_date/ for having time/date sensors available.

According to template documentation using now() will cause templates to be refreshed at the start of every new minute.

1 Like

Yes this is a recent change. In 0.117 I believe