Skip to content

Commit e57642e

Browse files
author
Philip de Nier
committed
Add a Timestamp.__float__ method
This allows float(Timestamp) to be used instead of Timestamp.to_float. This helps to convert TimeRange.length into a float in one go by doing float(TimeRange.length). sem-ver: feature
1 parent b7ab74c commit e57642e

2 files changed

Lines changed: 9 additions & 1 deletion

File tree

mediatimestamp/immutable/timestamp.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,7 @@ def to_tai_sec_frac(self, fixed_size: bool = False) -> str:
429429
def to_float(self) -> float:
430430
""" Convert to a floating point number of seconds
431431
"""
432-
return self._value / Timestamp.MAX_NANOSEC
432+
return self.__float__()
433433

434434
def to_datetime(self) -> datetime:
435435
sec, nsec, sign, leap = self.to_unix()
@@ -665,6 +665,9 @@ def __floordiv__(self, anint: int) -> "Timestamp":
665665
ns = self._value // anint
666666
return Timestamp(ns=ns)
667667

668+
def __float__(self):
669+
return self._value / Timestamp.MAX_NANOSEC
670+
668671
def _get_fractional_seconds(self, fixed_size: bool = False) -> str:
669672
div = self.MAX_NANOSEC // 10
670673
rem = self.ns

tests/test_timerange.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,11 @@ def test_length_negative(self):
489489

490490
self._check_length(a, b, c)
491491

492+
def test_length_float(self):
493+
self.assertEqual(TimeRange.eternity().length, float("inf"))
494+
self.assertEqual(float(TimeRange.eternity().length), float("inf"))
495+
self.assertEqual(float(TimeRange.from_str("[0:0_1:0)").length), 1.0)
496+
492497
def test_repr(self):
493498
"""This tests that the repr function turns time ranges into `eval`-able strings."""
494499
test_trs = [

0 commit comments

Comments
 (0)