Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions dissect/util/ts.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,27 @@ def dostimestamp(ts: int, centiseconds: int = 0, swap: bool = False) -> datetime
seconds + extra_seconds,
microseconds,
)


def golangtimestamp(raw: bytes) -> datetime:
"""Unmarshal golang ``time.Time`` bytes to a :class:`datetime` object.

.. code-block::

struct datetime {
uint8 version; // 1 or 2
uint64 seconds; // since 01-01-0001 (Gregorian)
uint32 nanoseconds;
int16 timezone; // offset in minutes or -1 if UTC
// uint8 zone_tracker; // specific to version 2
};

References:
- https://pkg.go.dev/time
"""
_version, seconds, nanoseconds, offset = struct.unpack(">BQIh", raw)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you cache the structure in something like _GOTIME = struct.Struct(">BQIh")? You can place it just above this function.


timestamp = seconds - 62_135_596_800
tz = timezone.utc if offset == -1 else timezone(timedelta(minutes=offset))
dt = datetime.fromtimestamp(timestamp, tz=tz)
return dt.replace(microsecond=nanoseconds // 1000)
6 changes: 6 additions & 0 deletions tests/test_ts.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,9 @@ def test_negative_timestamps(imported_ts: ModuleType) -> None:
1969, 12, 17, 22, 59, 47, 786787, tzinfo=timezone.utc
)
assert imported_ts.from_unix(-0xDEADBEEF) == datetime(1851, 8, 13, 2, 4, 1, tzinfo=timezone.utc)


def test_golang_timestamp(ts: ModuleType) -> None:
"""Test if we can convert golang ``Time.time`` marshalled bytes to a datetime object."""
timestamp = bytes.fromhex("010000000ee2221c201f08a2f6ffff")
assert ts.golangtimestamp(timestamp) == datetime(2026, 8, 27, 11, 53, 4, 520659, tzinfo=timezone.utc)