Skip to content
Open
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
16 changes: 14 additions & 2 deletions src/firebase_functions/private/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,8 +369,20 @@ def normalize_timestamp_string(time: str) -> str:
return f"{prefix}.{digits[:6]}{timezone}"


def timestamp_conversion(time: str) -> _dt.datetime:
"""Converts an ISO 8601 timestamp and returns a timezone-aware datetime object."""
def timestamp_conversion(time: str | dict) -> _dt.datetime:
"""Converts an ISO 8601 timestamp or dictionary and returns a timezone-aware datetime object."""
if isinstance(time, dict):
seconds = time.get("seconds")
seconds = int(seconds) if seconds is not None else 0

nanos = time.get("nanos")
if nanos is None:
nanos = time.get("nanoseconds")
nanos = int(nanos) if nanos is not None else 0

base_dt = _dt.datetime.fromtimestamp(seconds, tz=_dt.timezone.utc)
return base_dt + _dt.timedelta(microseconds=nanos // 1000)

normalized_time = normalize_timestamp_string(time)
if "." not in normalized_time:
return _dt.datetime.strptime(normalized_time, "%Y-%m-%dT%H:%M:%S%z")
Expand Down
8 changes: 8 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ def test_timestamp_conversion_supported_formats():
Testing shared timestamp conversion handles supported RTDB and CloudEvent formats.
"""
timestamps = [
(
{"seconds": 1712750400, "nanos": 0},
_dt.datetime(2024, 4, 10, 12, 0, tzinfo=_dt.timezone.utc),
),
(
{"seconds": 1712750400, "nanos": 123456000},
_dt.datetime(2024, 4, 10, 12, 0, 0, 123456, tzinfo=_dt.timezone.utc),
),
(
"2024-04-10T12:00:00.000Z",
_dt.datetime(2024, 4, 10, 12, 0, tzinfo=_dt.timezone.utc),
Expand Down
Loading