Skip to content

Commit

Permalink
duration macro added (#23690)
Browse files Browse the repository at this point in the history
Signed-off-by: Sergey Chvalyuk <grubberr@gmail.com>
  • Loading branch information
grubberr authored Mar 2, 2023
1 parent 40fde3a commit bfe8ccb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from typing import Union

from dateutil import parser
from isodate import parse_duration

"""
This file contains macros that can be evaluated by a `JinjaInterpolation` object
Expand Down Expand Up @@ -96,6 +97,16 @@ def day_delta(num_days: int, format: str = "%Y-%m-%dT%H:%M:%S.%f%z") -> str:
return (datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=num_days)).strftime(format)


def duration(datestring: str):
"""
Converts ISO8601 duration to datetime.timedelta
Usage:
`"{{ now_utc() - duration('P1D') }}"`
"""
return parse_duration(datestring)


def format_datetime(dt: Union[str, datetime.datetime], format: str):
"""
Converts datetime to another format
Expand All @@ -108,5 +119,5 @@ def format_datetime(dt: Union[str, datetime.datetime], format: str):
return parser.parse(dt).strftime(format)


_macros_list = [now_local, now_utc, today_utc, timestamp, max, day_delta, format_datetime]
_macros_list = [now_local, now_utc, today_utc, timestamp, max, day_delta, duration, format_datetime]
macros = {f.__name__: f for f in _macros_list}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
("test_max", "max", True),
("test_day_delta", "day_delta", True),
("test_format_datetime", "format_datetime", True),
("test_duration", "duration", True),
("test_not_a_macro", "thisisnotavalidmacro", False),
],
)
Expand All @@ -31,3 +32,8 @@ def test_format_datetime():
format_datetime = macros["format_datetime"]
assert format_datetime("2022-01-01T01:01:01Z", "%Y-%m-%d") == "2022-01-01"
assert format_datetime(datetime.datetime(2022, 1, 1, 1, 1, 1), "%Y-%m-%d") == "2022-01-01"


def test_duration():
duration = macros["duration"]
assert duration("P1D") == datetime.timedelta(days=1)

0 comments on commit bfe8ccb

Please sign in to comment.