Skip to content

Commit 24be60e

Browse files
Omit 0 as fractional epoch seconds
This updates unix timestamp serialization to omit fractional seconds when that fraction is 0.
1 parent 35b4e18 commit 24be60e

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

codegen/smithy-python-codegen/src/main/java/software/amazon/smithy/python/codegen/integration/HttpProtocolGeneratorUtils.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@ public static String getTimestampInputParam(
6060
writer.addImport("smithy_python.utils", "serialize_rfc3339");
6161
return String.format("serialize_rfc3339(%s)", result);
6262
case EPOCH_SECONDS:
63-
return "str(" + result + ".timestamp())";
63+
writer.addDependency(SmithyPythonDependency.SMITHY_PYTHON);
64+
writer.addImport("smithy_python.utils", "serialize_epoch_seconds");
65+
return String.format("serialize_epoch_seconds(%s)", result);
6466
case HTTP_DATE:
6567
writer.addStdlibImport("email.utils", "format_datetime");
6668
return "format_datetime(" + result + ", usegmt=True)";

python-packages/smithy-python/smithy_python/utils.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,17 @@ def serialize_rfc3339(given: datetime) -> str:
166166
return given.strftime(RFC3339_MICRO)
167167
else:
168168
return given.strftime(RFC3339)
169+
170+
171+
def serialize_epoch_seconds(given: datetime) -> str:
172+
"""Serializes a datetime into a string containing the epoch seconds.
173+
174+
If ``microseconds`` is 0, no fractional part is serialized.
175+
176+
:param given: The datetime to serialize.
177+
:retursn: A string containing the seconds since the UNIX epoch.
178+
"""
179+
result = given.timestamp()
180+
if given.microsecond == 0:
181+
result = int(result)
182+
return str(result)

python-packages/smithy-python/tests/unit/test_utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
ensure_utc,
1111
expect_type,
1212
limited_parse_float,
13+
serialize_epoch_seconds,
1314
serialize_float,
1415
serialize_rfc3339,
1516
split_every,
@@ -189,3 +190,17 @@ def test_serialize_float(given: float | Decimal, expected: str) -> None:
189190
)
190191
def test_serialize_rfc3339(given: datetime, expected: str) -> None:
191192
assert serialize_rfc3339(given) == expected
193+
194+
195+
@pytest.mark.parametrize(
196+
"given, expected",
197+
[
198+
(datetime(2017, 1, 1, tzinfo=timezone.utc), "1483228800"),
199+
(
200+
datetime(2017, 1, 1, microsecond=1, tzinfo=timezone.utc),
201+
"1483228800.000001",
202+
),
203+
],
204+
)
205+
def test_serialize_epoch_seconds(given: datetime, expected: str) -> None:
206+
assert serialize_epoch_seconds(given) == expected

0 commit comments

Comments
 (0)