Skip to content

Commit ba4c2e1

Browse files
committed
Adding support for converting a timedelta to a duration.
1 parent 5a42aca commit ba4c2e1

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

core/google/cloud/_helpers.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from threading import local as Local
2828

2929
import google.auth
30+
from google.protobuf import duration_pb2
3031
from google.protobuf import timestamp_pb2
3132
import google_auth_httplib2
3233

@@ -424,6 +425,20 @@ def _datetime_to_pb_timestamp(when):
424425
return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)
425426

426427

428+
def _timedelta_to_pb_duration(timedelta):
429+
"""Convert a timedelta object to a Duration protobuf.
430+
431+
:type timedelta: :class:`datetime.timedelta`
432+
:param timedelta: the timedelta to convert
433+
434+
:rtype: :class:`google.protobuf.duration_pb2.Duration`
435+
:returns: A duraiton protobuf corresponding to the object.
436+
"""
437+
seconds = int(timedelta.total_seconds())
438+
nanos = timedelta.microseconds * 10**3
439+
return duration_pb2.Duration(seconds=seconds, nanos=nanos)
440+
441+
427442
def _name_from_project_path(path, project, template):
428443
"""Validate a URI path and get the leaf object's name.
429444

core/unit_tests/test__helpers.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,29 @@ def test_it(self):
594594
self.assertEqual(self._call_fut(dt_stamp), timestamp)
595595

596596

597+
class Test__timedelta_to_pb_duration(unittest.TestCase):
598+
599+
def _callFUT(self, when):
600+
from google.cloud._helpers import _timedelta_to_pb_duration
601+
return _timedelta_to_pb_duration(when)
602+
603+
def test_wo_days(self):
604+
import datetime
605+
from google.protobuf.duration_pb2 import Duration
606+
607+
timedelta = datetime.timedelta(seconds=1, microseconds=123456)
608+
duration = Duration(seconds=1, nanos=123456000)
609+
self.assertEqual(self._callFUT(timedelta), duration)
610+
611+
def test_w_days(self):
612+
import datetime
613+
from google.protobuf.duration_pb2 import Duration
614+
615+
timedelta = datetime.timedelta(days=1, seconds=22, microseconds=123456)
616+
duration = Duration(seconds=86422, nanos=123456000)
617+
self.assertEqual(self._callFUT(timedelta), duration)
618+
619+
597620
class Test__name_from_project_path(unittest.TestCase):
598621

599622
PROJECT = 'PROJECT'

0 commit comments

Comments
 (0)