Skip to content

Commit 2e5c30a

Browse files
author
Jeff Whitaker
committed
Merge pull request Unidata#252 from takluyver/datetime-compare
Make datetime objects comparable
2 parents 013a942 + 046e998 commit 2e5c30a

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

netcdftime.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ def __repr__(self):
5252
return self.strftime(self.format)
5353
def __eq__(self, date):
5454
return self.strftime('%Y-%m-%d %H:%M:%S') == date.strftime('%Y-%m-%d %H:%M:%S')
55+
56+
def __lt__(self, other):
57+
if isinstance(other, (datetime, real_datetime)):
58+
return self.strftime('%Y-%m-%d %H:%M:%S') < other.strftime('%Y-%m-%d %H:%M:%S')
59+
return NotImplemented
60+
61+
def __gt__(self, other):
62+
if isinstance(other, (datetime, real_datetime)):
63+
return self.strftime('%Y-%m-%d %H:%M:%S') > other.strftime('%Y-%m-%d %H:%M:%S')
64+
return NotImplemented
5565

5666

5767
def JulianDayFromDate(date,calendar='standard'):

test/tst_netcdftime.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,13 @@ def runTest(self):
184184
# check timezone offset
185185
d = datetime(2012,2,29,15)
186186
assert(self.cdftime_mixed.date2num(d)-self.cdftime_mixed_tz.date2num(d) == 6)
187+
188+
# Check comparisons with Python datetime types
189+
d1 = num2date(0, 'days since 1000-01-01', 'standard')
190+
d2 = datetime(2000, 1, 1)
191+
d3 = num2date(0, 'days since 3000-01-01', 'standard')
192+
assert d1 < d2
193+
assert d2 < d3
187194

188195

189196
class TestDate2index(unittest.TestCase):

0 commit comments

Comments
 (0)