Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Low CDK: duration macro added #23690

Merged
merged 1 commit into from
Mar 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)