From 4747129b881e767c8769ded5f7b1b331c21954a6 Mon Sep 17 00:00:00 2001 From: Piotr Pauksztelo Date: Fri, 29 Nov 2024 14:56:25 +0100 Subject: [PATCH] Add option to TimeParser to get current timestamp with timezone --- logprep/util/time.py | 9 +++++++-- tests/unit/util/test_time.py | 19 +++++++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/logprep/util/time.py b/logprep/util/time.py index 66046ca22..75a57dc86 100644 --- a/logprep/util/time.py +++ b/logprep/util/time.py @@ -61,15 +61,20 @@ def from_timestamp(cls, timestamp: Union[int, float]) -> datetime: return time_object @classmethod - def now(cls) -> datetime: + def now(cls, timezone: tzinfo = None) -> datetime: """returns the current time + Parameters + ---------- + timezone : tzinfo + the timezone to use for the timestamp + Returns ------- datetime current date and time as datetime """ - time_object = datetime.now() + time_object = datetime.now(timezone) time_object = cls._set_utc_if_timezone_is_missing(time_object) return time_object diff --git a/tests/unit/util/test_time.py b/tests/unit/util/test_time.py index 4599f6fda..f3d3c876c 100644 --- a/tests/unit/util/test_time.py +++ b/tests/unit/util/test_time.py @@ -60,11 +60,22 @@ def test_from_format_returns(self, source, format_str, expected): for attribute, value in expected.items(): assert getattr(timestamp, attribute) == value + @pytest.mark.parametrize("timezone", [None, ZoneInfo("UTC"), ZoneInfo("Europe/Berlin")]) + def test_has_utc_if_timezone_was_set(self, timezone): + datetime_time = datetime.now(timezone) + time_parser_time = TimeParser.now(timezone) + assert time_parser_time.second == pytest.approx(datetime_time.second, abs=1) + if timezone is None: + assert time_parser_time.tzinfo == ZoneInfo("UTC") + else: + assert time_parser_time.tzinfo == timezone + def test_set_utc_if_timezone_is_missing_sets_timezone(self): - time_object = datetime.now() - assert time_object.tzinfo is None - time_object = TimeParser._set_utc_if_timezone_is_missing(time_object) - assert time_object.tzinfo is ZoneInfo("UTC") + datetime_time = datetime.now() + assert datetime_time.tzinfo is None + time_parser_time = TimeParser._set_utc_if_timezone_is_missing(datetime_time) + assert time_parser_time.tzinfo is ZoneInfo("UTC") + assert time_parser_time.second == pytest.approx(datetime_time.second, abs=1) @pytest.mark.parametrize( "timestamp, source_format, source_timezone, expected_timezone_name, expected",