Skip to content

Commit

Permalink
Adding support for converting a timedelta to a duration.
Browse files Browse the repository at this point in the history
  • Loading branch information
dhermes committed Jan 20, 2017
1 parent 5a42aca commit ba4c2e1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions core/google/cloud/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from threading import local as Local

import google.auth
from google.protobuf import duration_pb2
from google.protobuf import timestamp_pb2
import google_auth_httplib2

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


def _timedelta_to_pb_duration(timedelta):
"""Convert a timedelta object to a Duration protobuf.
:type timedelta: :class:`datetime.timedelta`
:param timedelta: the timedelta to convert
:rtype: :class:`google.protobuf.duration_pb2.Duration`
:returns: A duraiton protobuf corresponding to the object.
"""
seconds = int(timedelta.total_seconds())
nanos = timedelta.microseconds * 10**3
return duration_pb2.Duration(seconds=seconds, nanos=nanos)


def _name_from_project_path(path, project, template):
"""Validate a URI path and get the leaf object's name.
Expand Down
23 changes: 23 additions & 0 deletions core/unit_tests/test__helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,29 @@ def test_it(self):
self.assertEqual(self._call_fut(dt_stamp), timestamp)


class Test__timedelta_to_pb_duration(unittest.TestCase):

def _callFUT(self, when):
from google.cloud._helpers import _timedelta_to_pb_duration
return _timedelta_to_pb_duration(when)

def test_wo_days(self):
import datetime
from google.protobuf.duration_pb2 import Duration

timedelta = datetime.timedelta(seconds=1, microseconds=123456)
duration = Duration(seconds=1, nanos=123456000)
self.assertEqual(self._callFUT(timedelta), duration)

def test_w_days(self):
import datetime
from google.protobuf.duration_pb2 import Duration

timedelta = datetime.timedelta(days=1, seconds=22, microseconds=123456)
duration = Duration(seconds=86422, nanos=123456000)
self.assertEqual(self._callFUT(timedelta), duration)


class Test__name_from_project_path(unittest.TestCase):

PROJECT = 'PROJECT'
Expand Down

0 comments on commit ba4c2e1

Please sign in to comment.