Commit 73992b54 by Xiaofei Wang Committed by Copybara-Service

Internal change

PiperOrigin-RevId: 453518316
parent 4b5def2c
......@@ -115,15 +115,28 @@ struct type_caster<absl::Duration> {
// Conversion part 1 (Python->C++)
bool load(handle src, bool convert) {
// Ensure that absl::Duration is converted from a Python datetime.timedelta.
if (!convert || !hasattr(src, "days") || !hasattr(src, "seconds") ||
!hasattr(src, "microseconds")) {
if (!convert) {
return false;
}
value = absl::Hours(24 * GetInt64Attr(src, "days")) +
absl::Seconds(GetInt64Attr(src, "seconds")) +
absl::Microseconds(GetInt64Attr(src, "microseconds"));
return true;
if (PyFloat_Check(src.ptr())) {
value = absl::Seconds(src.cast<double>());
return true;
} else if (PyLong_Check(src.ptr())) {
value = absl::Seconds(src.cast<int64_t>());
return true;
} else {
// Ensure that absl::Duration is converted from a Python
// datetime.timedelta.
if (!hasattr(src, "days") || !hasattr(src, "seconds") ||
!hasattr(src, "microseconds")) {
return false;
}
value = absl::Hours(24 * GetInt64Attr(src, "days")) +
absl::Seconds(GetInt64Attr(src, "seconds")) +
absl::Microseconds(GetInt64Attr(src, "microseconds"));
return true;
}
return false;
}
// Conversion part 2 (C++ -> Python)
......
......@@ -46,6 +46,19 @@ class AbslTimeTest(parameterized.TestCase):
duration = datetime.timedelta(seconds=self.NEGATIVE_SECS)
self.assertTrue(absl_example.check_duration(duration, self.NEGATIVE_SECS))
def test_pass_float_duration(self):
self.assertTrue(
absl_example.check_duration(self.POSITIVE_SECS, self.POSITIVE_SECS))
def test_pass_integer_duration(self):
self.assertTrue(
absl_example.check_duration(self.SECONDS_IN_DAY, self.SECONDS_IN_DAY))
def test_duration_integer_overflow(self):
duration = 2**129
with self.assertRaises(RuntimeError):
absl_example.check_duration(duration, duration)
def test_return_datetime(self):
secs = self.TEST_DATETIME.timestamp()
local_tz = tz.gettz()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment