Append leading zeros for nanosecond precision DateTimes (#7663)
diff --git a/google/api_core/datetime_helpers.py b/google/api_core/datetime_helpers.py
index b0d9105..84c1bb7 100644
--- a/google/api_core/datetime_helpers.py
+++ b/google/api_core/datetime_helpers.py
@@ -222,7 +222,7 @@
"""
if self._nanosecond == 0:
return to_rfc3339(self)
- nanos = str(self._nanosecond).rstrip("0")
+ nanos = str(self._nanosecond).rjust(9, '0').rstrip("0")
return "{}.{}Z".format(self.strftime(_RFC3339_NO_FRACTION), nanos)
@classmethod
diff --git a/tests/unit/test_datetime_helpers.py b/tests/unit/test_datetime_helpers.py
index e5220ae..a53086e 100644
--- a/tests/unit/test_datetime_helpers.py
+++ b/tests/unit/test_datetime_helpers.py
@@ -204,6 +204,11 @@
assert stamp.rfc3339() == "2016-12-20T21:13:47.123456Z"
@staticmethod
+ def test_rfc3339_wo_nanos_w_leading_zero():
+ stamp = datetime_helpers.DatetimeWithNanoseconds(2016, 12, 20, 21, 13, 47, 1234)
+ assert stamp.rfc3339() == "2016-12-20T21:13:47.001234Z"
+
+ @staticmethod
def test_rfc3339_w_nanos():
stamp = datetime_helpers.DatetimeWithNanoseconds(
2016, 12, 20, 21, 13, 47, nanosecond=123456789
@@ -211,6 +216,13 @@
assert stamp.rfc3339() == "2016-12-20T21:13:47.123456789Z"
@staticmethod
+ def test_rfc3339_w_nanos_w_leading_zero():
+ stamp = datetime_helpers.DatetimeWithNanoseconds(
+ 2016, 12, 20, 21, 13, 47, nanosecond=1234567
+ )
+ assert stamp.rfc3339() == "2016-12-20T21:13:47.001234567Z"
+
+ @staticmethod
def test_rfc3339_w_nanos_no_trailing_zeroes():
stamp = datetime_helpers.DatetimeWithNanoseconds(
2016, 12, 20, 21, 13, 47, nanosecond=100000000
@@ -218,6 +230,13 @@
assert stamp.rfc3339() == "2016-12-20T21:13:47.1Z"
@staticmethod
+ def test_rfc3339_w_nanos_w_leading_zero_and_no_trailing_zeros():
+ stamp = datetime_helpers.DatetimeWithNanoseconds(
+ 2016, 12, 20, 21, 13, 47, nanosecond=1234500
+ )
+ assert stamp.rfc3339() == "2016-12-20T21:13:47.0012345Z"
+
+ @staticmethod
def test_from_rfc3339_w_invalid():
stamp = "2016-12-20T21:13:47"
with pytest.raises(ValueError):