Skip to content

Commit ca8822b

Browse files
gleepercrwilcox
authored andcommitted
Append leading zeros for nanosecond precision DateTimes (#7663)
1 parent e6eb1c5 commit ca8822b

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

google/api_core/datetime_helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def rfc3339(self):
222222
"""
223223
if self._nanosecond == 0:
224224
return to_rfc3339(self)
225-
nanos = str(self._nanosecond).rstrip("0")
225+
nanos = str(self._nanosecond).rjust(9, '0').rstrip("0")
226226
return "{}.{}Z".format(self.strftime(_RFC3339_NO_FRACTION), nanos)
227227

228228
@classmethod

tests/unit/test_datetime_helpers.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,20 +203,39 @@ def test_rfc3339_wo_nanos():
203203
stamp = datetime_helpers.DatetimeWithNanoseconds(2016, 12, 20, 21, 13, 47, 123456)
204204
assert stamp.rfc3339() == "2016-12-20T21:13:47.123456Z"
205205

206+
@staticmethod
207+
def test_rfc3339_wo_nanos_w_leading_zero():
208+
stamp = datetime_helpers.DatetimeWithNanoseconds(2016, 12, 20, 21, 13, 47, 1234)
209+
assert stamp.rfc3339() == "2016-12-20T21:13:47.001234Z"
210+
206211
@staticmethod
207212
def test_rfc3339_w_nanos():
208213
stamp = datetime_helpers.DatetimeWithNanoseconds(
209214
2016, 12, 20, 21, 13, 47, nanosecond=123456789
210215
)
211216
assert stamp.rfc3339() == "2016-12-20T21:13:47.123456789Z"
212217

218+
@staticmethod
219+
def test_rfc3339_w_nanos_w_leading_zero():
220+
stamp = datetime_helpers.DatetimeWithNanoseconds(
221+
2016, 12, 20, 21, 13, 47, nanosecond=1234567
222+
)
223+
assert stamp.rfc3339() == "2016-12-20T21:13:47.001234567Z"
224+
213225
@staticmethod
214226
def test_rfc3339_w_nanos_no_trailing_zeroes():
215227
stamp = datetime_helpers.DatetimeWithNanoseconds(
216228
2016, 12, 20, 21, 13, 47, nanosecond=100000000
217229
)
218230
assert stamp.rfc3339() == "2016-12-20T21:13:47.1Z"
219231

232+
@staticmethod
233+
def test_rfc3339_w_nanos_w_leading_zero_and_no_trailing_zeros():
234+
stamp = datetime_helpers.DatetimeWithNanoseconds(
235+
2016, 12, 20, 21, 13, 47, nanosecond=1234500
236+
)
237+
assert stamp.rfc3339() == "2016-12-20T21:13:47.0012345Z"
238+
220239
@staticmethod
221240
def test_from_rfc3339_w_invalid():
222241
stamp = "2016-12-20T21:13:47"

0 commit comments

Comments
 (0)