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:
- Query JSON Test with a
rest
sensor and avalue_template:
. - Use a
time_date
sensor and a template{{ strptime(states('sensor.date'), '%Y-%m-%d').year }}
. - Write a script in language X and use it with the
command
sensor or usedate +"%Y"
as acommand:
.
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
andnow().hour
- For the date:
now().day
,now().month
andnow().year
- Misc:
now().weekday()
andnow().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.