feat: add timestamp_to_datetime jinja template filter (#5303)

Related to https://github.com/grafana/support-escalations/issues/13670

Given a payload like this:

```
{  
    "Sometime": "1730893740"  
}
```

the following template expression:

`{{ payload.Sometime | int | timestamp_to_datetime }}`

will render as:

`2024-11-06 11:49:00`
This commit is contained in:
Matias Bordese 2024-11-28 08:20:21 -03:00 committed by GitHub
parent fb0ede6656
commit 6a65ddd6e7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 21 additions and 0 deletions

View file

@ -94,6 +94,7 @@ Grafana OnCall enhances Jinja with additional functions:
- `datetimeparse`: Converts string to datetime according to strftime format codes (`%H:%M / %d-%m-%Y` by default)
- `timedeltaparse`: Converts a time range (e.g., `5s`, `2m`, `6h`, `3d`) to a timedelta that can be added to or subtracted from a datetime
- Usage example: `{% set delta = alert.window | timedeltaparse %}{{ alert.startsAt | iso8601_to_time - delta | datetimeformat }}`
- `timestamp_to_datetime`: Converts a Unix/Epoch time to a datetime object
- `regex_replace`: Performs a regex find and replace
- `regex_match`: Performs a regex match, returns `True` or `False`
- Usage example: `{{ payload.ruleName | regex_match(".*") }}`

View file

@ -30,6 +30,13 @@ def datetimeformat_as_timezone(value, format="%H:%M / %d-%m-%Y", tz="UTC"):
return None
def timestamp_to_datetime(value):
try:
return datetime.fromtimestamp(value)
except (ValueError, AttributeError, TypeError):
return None
def iso8601_to_time(value):
try:
return parse_datetime(value)

View file

@ -15,6 +15,7 @@ from .filters import (
regex_replace,
regex_search,
timedeltaparse,
timestamp_to_datetime,
to_pretty_json,
)
@ -39,3 +40,4 @@ jinja_template_env.filters["regex_search"] = regex_search
jinja_template_env.filters["json_dumps"] = json_dumps
jinja_template_env.filters["b64decode"] = b64decode
jinja_template_env.filters["parse_json"] = parse_json
jinja_template_env.filters["timestamp_to_datetime"] = timestamp_to_datetime

View file

@ -66,6 +66,17 @@ def test_apply_jinja_template_iso8601_to_time():
assert result == expected
def test_apply_jinja_template_timestamp_to_datetime():
payload = {"sometime": 1730893740}
result = apply_jinja_template(
"{{ payload.sometime | timestamp_to_datetime }}",
payload,
)
expected = str(datetime.fromtimestamp(payload["sometime"]))
assert result == expected
def test_apply_jinja_template_datetimeformat():
payload = {"aware": "2023-05-28 23:11:12+0000", "naive": "2023-05-28 23:11:12"}