|
1 | 1 | import datetime
|
| 2 | +import typing |
2 | 3 |
|
| 4 | +import betterproto2 |
3 | 5 | import dateutil.parser
|
4 | 6 |
|
5 | 7 | from betterproto2_compiler.lib.google.protobuf import Timestamp as VanillaTimestamp
|
|
8 | 10 | class Timestamp(VanillaTimestamp):
|
9 | 11 | @classmethod
|
10 | 12 | 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 | + |
11 | 18 | # manual epoch offset calulation to avoid rounding errors,
|
12 | 19 | # to support negative timestamps (before 1970) and skirt
|
13 | 20 | # around datetime bugs (apparently 0 isn't a year in [0, 9999]??)
|
@@ -56,5 +63,23 @@ def from_dict(cls, value):
|
56 | 63 |
|
57 | 64 | return super().from_dict(value)
|
58 | 65 |
|
| 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 | + |
59 | 84 | def to_wrapped(self) -> datetime.datetime:
|
60 | 85 | return self.to_datetime()
|
0 commit comments