Skip to content

Commit fd2dfb9

Browse files
Petro31frenck
andcommitted
Add Relative_time and today_at updates (#25986)
Co-authored-by: Franck Nijhof <git@frenck.dev>
1 parent 74a4110 commit fd2dfb9

File tree

1 file changed

+35
-34
lines changed

1 file changed

+35
-34
lines changed

source/_docs/configuration/templating.markdown

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ Not supported in [limited templates](#limited-templates).
123123

124124
<div class='note warning'>
125125

126-
Avoid using `states.sensor.temperature.state`, instead use `states('sensor.temperature')`. It is strongly advised to use the `states()`, `is_state()`, `state_attr()` and `is_state_attr()` as much as possible, to avoid errors and error message when the entity isn't ready yet (e.g., during Home Assistant startup).
126+
Avoid using `states.sensor.temperature.state`, instead use `states('sensor.temperature')`. It is strongly advised to use the `states()`, `is_state()`, `state_attr()` and `is_state_attr()` as much as possible, to avoid errors and error message when the entity isn't ready yet (e.g., during Home Assistant startup).
127127

128128
</div>
129129

@@ -554,7 +554,7 @@ For example, if you wanted to select a field from `trigger` in an automation bas
554554

555555
### Time
556556

557-
`now()` and `utcnow()` are not supported in [limited templates](#limited-templates).
557+
`now()`, `relative_time()`, `today_at()`, and `utcnow()` are not supported in [limited templates](#limited-templates).
558558

559559
- `now()` returns a datetime object that represents the current time in your time zone.
560560
- You can also use: `now().second`, `now().minute`, `now().hour`, `now().day`, `now().month`, `now().year`, `now().weekday()` and `now().isoweekday()` and other [`datetime`](https://docs.python.org/3.8/library/datetime.html#datetime.datetime) attributes and functions.
@@ -564,41 +564,44 @@ For example, if you wanted to select a field from `trigger` in an automation bas
564564
- Using `utcnow()` will cause templates to be refreshed at the start of every new minute.
565565
- `today_at(value)` converts a string containing a military time format to a datetime object with today's date in your time zone.
566566

567-
{% raw %}
567+
- Using `today_at()` will cause templates to be refreshed at the start of every new minute.
568568

569-
```yaml
570-
# Is the current time past 10:15?
571-
{{ now() > today_at("10:15") }}
572-
```
569+
{% raw %}
573570

574-
{% endraw %}
571+
```text
572+
# Is the current time past 10:15?
573+
{{ now() > today_at("10:15") }}
574+
```
575+
576+
{% endraw %}
575577

576578
- `as_datetime()` converts a string containing a timestamp, or valid UNIX timestamp, to a datetime object.
577579
- `as_timestamp(value, default)` converts datetime object or string to UNIX timestamp. If that fails, returns the `default` value, or if omitted raises an error. This function can also be used as a filter.
578580
- `as_local()` converts datetime object to local time. This function can also be used as a filter.
579581
- `strptime(string, format, default)` parses a string based on a [format](https://docs.python.org/3.10/library/datetime.html#strftime-and-strptime-behavior) and returns a datetime object. If that fails, it returns the `default` value or, if omitted, raises an error.
580-
- `relative_time` converts datetime object to its human-friendly "age" string. The age can be in second, minute, hour, day, month or year (but only the biggest unit is considered, e.g., if it's 2 days and 3 hours, "2 days" will be returned). Note that it only works for dates _in the past_.
582+
- `relative_time` converts datetime object to its human-friendly "age" string. The age can be in second, minute, hour, day, month or year (but only the biggest unit is considered, e.g., if it's 2 days and 3 hours, "2 days" will be returned). Note that it only works for dates _in the past_.
583+
- Using `relative_time()` will cause templates to be refreshed at the start of every new minute.
581584
- `timedelta` returns a timedelta object and accepts the same arguments as the Python `datetime.timedelta` function -- days, seconds, microseconds, milliseconds, minutes, hours, weeks.
582585

583-
{% raw %}
586+
{% raw %}
584587

585-
```yaml
586-
# 77 minutes before current time.
587-
{{ now() - timedelta( hours = 1, minutes = 17 ) }}
588-
```
588+
```text
589+
# 77 minutes before current time.
590+
{{ now() - timedelta( hours = 1, minutes = 17 ) }}
591+
```
589592

590-
{% endraw %}
593+
{% endraw %}
591594

592595
- `as_timedelta(string)` converts a string to a timedelta object. Expects data in the format `DD HH:MM:SS.uuuuuu`, `DD HH:MM:SS,uuuuuu`, or as specified by ISO 8601 (e.g. `P4DT1H15M20S` which is equivalent to `4 1:15:20`) or PostgreSQL’s day-time interval format (e.g. `3 days 04:05:06`) This function can also be used as a filter.
593596

594-
{% raw %}
597+
{% raw %}
595598

596-
```yaml
597-
# Renders to "00:10:00"
598-
{{ as_timedelta("PT10M") }}
599-
```
599+
```text
600+
# Renders to "00:10:00"
601+
{{ as_timedelta("PT10M") }}
602+
```
600603

601-
{% endraw %}
604+
{% endraw %}
602605

603606
- Filter `timestamp_local(default)` converts a UNIX timestamp to the ISO format string representation as date/time in your local timezone. If that fails, returns the `default` value, or if omitted raises an error. If a custom string format is needed in the string, use `timestamp_custom` instead.
604607
- Filter `timestamp_utc(default)` converts a UNIX timestamp to the ISO format string representation representation as date/time in UTC timezone. If that fails, returns the `default` value, or if omitted raises an error. If a custom string format is needed in the string, use `timestamp_custom` instead.
@@ -632,7 +635,7 @@ To fix it, enforce the ISO conversion via `isoformat()`:
632635

633636
{% raw %}
634637

635-
```yaml
638+
```text
636639
{{ 120 | timestamp_local }}
637640
```
638641

@@ -846,10 +849,8 @@ Some examples:
846849
```
847850
This more complex example uses the `contains` filter to match the current month with a list. In this case, it's used to generate a list of light theme to give to the `Input select: Set options` service.
848851

849-
850852
{% endraw %}
851853

852-
853854
### Numeric functions and filters
854855

855856
Some of these functions can also be used in a [filter](https://jinja.palletsprojects.com/en/latest/templates/#id11). This means they can act as a normal function like this `sqrt(2)`, or as part of a filter like this `2|sqrt`.
@@ -870,14 +871,14 @@ The numeric functions and filters raise an error if the input is not a valid num
870871
</div>
871872

872873
- `float(value, default)` function will attempt to convert the input to a `float`. If that fails, returns the `default` value, or if omitted raises an error.
873-
- `float(default)` filter will attempt to convert the input to a `float`. If that fails, returns the `default` value, or if omitted raises an error.
874+
- `float(default)` filter will attempt to convert the input to a `float`. If that fails, returns the `default` value, or if omitted raises an error.
874875
- `is_number` will return `True` if the input can be parsed by Python's `float` function and the parsed input is not `inf` or `nan`, in all other cases returns `False`. Note that a Python `bool` will return `True` but the strings `"True"` and `"False"` will both return `False`. Can be used as a filter.
875876
- `int(value, default)` function is similar to `float`, but converts to an `int` instead. Like `float`, it has a filter form, and an error is raised if the `default` value is omitted. Fractional part is discarded: `int("1.5")` is `1`.
876877
- `bool(value, default)` function converts the value to either `true` or `false`.
877-
The following values are considered to be `true`: boolean `true`, non-zero `int`s and `float`s, and the strings `"true"`, `"yes"`, `"on"`, `"enable"`, and `"1"` (case-insensitive). `false` is returned for the opposite values: boolean `false`, integer or floating-point `0`, and the strings `"false"`, `"no"`, `"off"`, `"disable"`, and `"0"` (also case-insensitive).
878-
If the value is not listed here, the function returns the `default` value, or if omitted raises an error.
879-
This function is intended to be used on states of [binary sensors](/integrations/binary_sensor/), [switches](/integrations/switch/), or similar entities, so its behavior is different from Python's built-in `bool` conversion, which would consider e.g. `"on"`, `"off"`, and `"unknown"` all to be `true`, but `""` to be `false`; if that is desired, use `not not value` or a similar construct instead.
880-
Like `float` and `int`, `bool` has a filter form. Using `none` as the default value is particularly useful in combination with the [immediate if filter](#immediate-if-iif): it can handle all three possible cases in a single line.
878+
The following values are considered to be `true`: boolean `true`, non-zero `int`s and `float`s, and the strings `"true"`, `"yes"`, `"on"`, `"enable"`, and `"1"` (case-insensitive). `false` is returned for the opposite values: boolean `false`, integer or floating-point `0`, and the strings `"false"`, `"no"`, `"off"`, `"disable"`, and `"0"` (also case-insensitive).
879+
If the value is not listed here, the function returns the `default` value, or if omitted raises an error.
880+
This function is intended to be used on states of [binary sensors](/integrations/binary_sensor/), [switches](/integrations/switch/), or similar entities, so its behavior is different from Python's built-in `bool` conversion, which would consider e.g. `"on"`, `"off"`, and `"unknown"` all to be `true`, but `""` to be `false`; if that is desired, use `not not value` or a similar construct instead.
881+
Like `float` and `int`, `bool` has a filter form. Using `none` as the default value is particularly useful in combination with the [immediate if filter](#immediate-if-iif): it can handle all three possible cases in a single line.
881882

882883
- `log(value, base, default)` will take the logarithm of the input. When the base is omitted, it defaults to `e` - the natural logarithm. If `value` or `base` can't be converted to a `float`, returns the `default` value, or if omitted raises an error. Can also be used as a filter.
883884
- `sin(value, default)` will return the sine of the input. If `value` can't be converted to a `float`, returns the `default` value, or if omitted raises an error. Can be used as a filter.
@@ -951,7 +952,7 @@ The other part of templating is processing incoming data. It allows you to modif
951952
It depends per integration or platform, but it is common to be able to define a template using the `value_template` configuration key. When a new value arrives, your template will be rendered while having access to the following values on top of the usual Home Assistant extensions:
952953

953954
| Variable | Description |
954-
|--------------|------------------------------------|
955+
| ------------ | ---------------------------------- |
955956
| `value` | The incoming value. |
956957
| `value_json` | The incoming value parsed as JSON. |
957958

@@ -969,7 +970,7 @@ The template for `on` would be:
969970
{% raw %}
970971

971972
```yaml
972-
'{{value_json.on}}'
973+
"{{value_json.on}}"
973974
```
974975

975976
{% endraw %}
@@ -1068,7 +1069,7 @@ With given payload:
10681069
{ "state": "ON", "temperature": 21.902 }
10691070
```
10701071

1071-
Template {% raw %}```{{ value_json.temperature | round(1) }}```{% endraw %} renders to `21.9`.
1072+
Template {% raw %}`{{ value_json.temperature | round(1) }}`{% endraw %} renders to `21.9`.
10721073

10731074
Additional the MQTT entity attributes `entity_id`, `name` and `this` can be used as variables in the template. The `this` attribute refers to the [entity state](/docs/configuration/state_object) of the MQTT item.
10741075

@@ -1082,7 +1083,7 @@ For service calls command templates are defined to format the outgoing MQTT payl
10821083

10831084
Example command template:
10841085

1085-
With given value `21.9` template {% raw %}```{"temperature": {{ value }} }```{% endraw %} renders to:
1086+
With given value `21.9` template {% raw %}`{"temperature": {{ value }} }`{% endraw %} renders to:
10861087

10871088
```json
10881089
{
@@ -1106,7 +1107,7 @@ The default priority of operators is that the filter (`|`) has priority over eve
11061107

11071108
{% raw %}
11081109

1109-
```yaml
1110+
```text
11101111
{{ states('sensor.temperature') | float / 10 | round(2) }}
11111112
```
11121113

0 commit comments

Comments
 (0)