Skip to content
This repository was archived by the owner on Jun 9, 2025. It is now read-only.

Commit 20eecb3

Browse files
committed
Improve timestamp support
1 parent a2c2b13 commit 20eecb3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/betterproto2_compiler/known_types/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
Timestamp.to_datetime,
1616
Timestamp.timestamp_to_json,
1717
Timestamp.from_dict,
18+
Timestamp.to_dict,
19+
Timestamp.from_wrapped,
1820
Timestamp.to_wrapped,
1921
],
2022
("google.protobuf", "Duration"): [Duration.from_timedelta, Duration.to_timedelta, Duration.delta_to_json],

src/betterproto2_compiler/known_types/timestamp.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import datetime
2+
import typing
23

4+
import betterproto2
35
import dateutil.parser
46

57
from betterproto2_compiler.lib.google.protobuf import Timestamp as VanillaTimestamp
@@ -8,6 +10,11 @@
810
class Timestamp(VanillaTimestamp):
911
@classmethod
1012
def from_datetime(cls, dt: datetime.datetime) -> "Timestamp":
13+
if not dt.tzinfo:
14+
raise ValueError("datetime must be timezone aware")
15+
16+
dt = dt.astimezone(datetime.timezone.utc)
17+
1118
# manual epoch offset calulation to avoid rounding errors,
1219
# to support negative timestamps (before 1970) and skirt
1320
# around datetime bugs (apparently 0 isn't a year in [0, 9999]??)
@@ -56,5 +63,23 @@ def from_dict(cls, value):
5663

5764
return super().from_dict(value)
5865

66+
# TODO typing
67+
def to_dict(
68+
self,
69+
*,
70+
output_format: betterproto2.OutputFormat = betterproto2.OutputFormat.PROTO_JSON,
71+
casing: betterproto2.Casing = betterproto2.Casing.CAMEL,
72+
include_default_values: bool = False,
73+
) -> dict[str, typing.Any] | typing.Any:
74+
print("ok")
75+
# If the output format is PYTHON, we should have kept the wraped type without building the real class
76+
assert output_format == betterproto2.OutputFormat.PROTO_JSON
77+
78+
return Timestamp.timestamp_to_json(self.to_datetime())
79+
80+
@staticmethod
81+
def from_wrapped(wrapped: datetime.datetime) -> "Timestamp":
82+
return Timestamp.from_datetime(wrapped)
83+
5984
def to_wrapped(self) -> datetime.datetime:
6085
return self.to_datetime()

0 commit comments

Comments
 (0)