Skip to content

Commit

Permalink
Add option to TimeParser to get current timestamp with timezone
Browse files Browse the repository at this point in the history
  • Loading branch information
ppcad committed Nov 29, 2024
1 parent af153a2 commit 4747129
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
9 changes: 7 additions & 2 deletions logprep/util/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
19 changes: 15 additions & 4 deletions tests/unit/util/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 4747129

Please sign in to comment.