Skip to content

Commit 67a5823

Browse files
authored
Tweak OTel timestamp utils (#3436)
1 parent 52fca29 commit 67a5823

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

sentry_sdk/integrations/opentelemetry/potel_span_processor.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from sentry_sdk import capture_event
88
from sentry_sdk.integrations.opentelemetry.utils import (
99
is_sentry_span,
10-
convert_otel_timestamp,
10+
convert_from_otel_timestamp,
1111
extract_span_data,
1212
)
1313
from sentry_sdk.integrations.opentelemetry.consts import (
@@ -141,8 +141,8 @@ def _root_span_to_transaction_event(self, span):
141141
# TODO-neel-potel tx source based on integration
142142
"transaction_info": {"source": "custom"},
143143
"contexts": contexts,
144-
"start_timestamp": convert_otel_timestamp(span.start_time),
145-
"timestamp": convert_otel_timestamp(span.end_time),
144+
"start_timestamp": convert_from_otel_timestamp(span.start_time),
145+
"timestamp": convert_from_otel_timestamp(span.end_time),
146146
} # type: Event
147147

148148
return event
@@ -168,8 +168,8 @@ def _span_to_json(self, span):
168168
"op": op,
169169
"description": description,
170170
"status": status,
171-
"start_timestamp": convert_otel_timestamp(span.start_time),
172-
"timestamp": convert_otel_timestamp(span.end_time),
171+
"start_timestamp": convert_from_otel_timestamp(span.start_time),
172+
"timestamp": convert_from_otel_timestamp(span.end_time),
173173
"origin": origin or SPAN_ORIGIN,
174174
} # type: dict[str, Any]
175175

sentry_sdk/integrations/opentelemetry/utils.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from sentry_sdk._types import TYPE_CHECKING
1515

1616
if TYPE_CHECKING:
17-
from typing import Optional, Mapping, Sequence
17+
from typing import Optional, Mapping, Sequence, Union
1818

1919

2020
GRPC_ERROR_MAP = {
@@ -72,11 +72,20 @@ def is_sentry_span(span):
7272
return False
7373

7474

75-
def convert_otel_timestamp(time):
75+
def convert_from_otel_timestamp(time):
7676
# type: (int) -> datetime
77+
"""Convert an OTel nanosecond-level timestamp to a datetime."""
7778
return datetime.fromtimestamp(time / 1e9, timezone.utc)
7879

7980

81+
def convert_to_otel_timestamp(time):
82+
# type: (Union[datetime.datetime, float]) -> int
83+
"""Convert a datetime to an OTel timestamp (with nanosecond precision)."""
84+
if isinstance(time, datetime):
85+
return int(time.timestamp() * 1e9)
86+
return int(time * 1e9)
87+
88+
8089
def extract_span_data(span):
8190
# type: (ReadableSpan) -> tuple[str, str, Optional[str], Optional[int], Optional[str]]
8291
op = span.name

0 commit comments

Comments
 (0)