Skip to content

Commit 0c5c84e

Browse files
committed
Fix period comparison to timedelta
1 parent b4a598f commit 0c5c84e

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

pendulum/period.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import operator
44
import pendulum
55

6-
from datetime import datetime, date
6+
from datetime import datetime, date, timedelta
77

88
from pendulum.utils._compat import _HAS_FOLD
99
from pendulum.utils._compat import decode
@@ -344,6 +344,17 @@ def __repr__(self):
344344
def __str__(self):
345345
return self.__repr__()
346346

347+
def _cmp(self, other):
348+
# Only needed for PyPy
349+
assert isinstance(other, timedelta)
350+
351+
if isinstance(other, Period):
352+
other = other.as_timedelta()
353+
354+
td = self.as_timedelta()
355+
356+
return 0 if td == other else 1 if td > other else -1
357+
347358
def _getstate(self, protocol=3):
348359
start, end = self.start, self.end
349360

tests/duration/test_behavior.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
import pickle
22
import pendulum
33

4+
from datetime import timedelta
5+
46

57
def test_pickle():
68
it = pendulum.duration(days=3, seconds=2456, microseconds=123456)
79
s = pickle.dumps(it)
810
it2 = pickle.loads(s)
911

1012
assert it == it2
13+
14+
15+
def test_comparison_to_timedelta():
16+
duration = pendulum.duration(days=3)
17+
18+
assert duration < timedelta(days=4)

tests/period/test_behavior.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import pickle
22
import pendulum
33

4+
from datetime import timedelta
5+
46

57
def test_pickle():
68
dt1 = pendulum.datetime(2016, 11, 18)
@@ -29,3 +31,12 @@ def test_pickle():
2931
assert p.start == p2.start
3032
assert p.end == p2.end
3133
assert p.invert == p2.invert
34+
35+
36+
def test_comparison_to_timedelta():
37+
dt1 = pendulum.datetime(2016, 11, 18)
38+
dt2 = pendulum.datetime(2016, 11, 20)
39+
40+
period = dt2 - dt1
41+
42+
assert period < timedelta(days=4)

0 commit comments

Comments
 (0)