Skip to content

Commit 6e8e7f5

Browse files
author
Sara Safavi
committed
let date_range filter handle dates given with and without timezones
1 parent 1c62ce7 commit 6e8e7f5

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

planet/api/filters.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,10 @@ def not_filter(*predicates):
100100
def date_range(field_name, **kwargs):
101101
'''Build a DateRangeFilter.
102102
103-
Predicate arguments accept a value str that in ISO-8601 format or a value
104-
that has a `isoformat` callable that returns an ISO-8601 str.
103+
Predicate arguments accept a str that is ISO-8601 format or a value
104+
that has an `isoformat` callable that returns an ISO-8601 compliant str.
105+
106+
If no timezone is provided, UTC is assumed for RFC 3339 compatability.
105107
106108
:raises: ValueError if predicate value does not parse
107109
@@ -116,7 +118,12 @@ def date_range(field_name, **kwargs):
116118
dt = strp_lenient(str(v))
117119
if dt is None:
118120
raise ValueError("unable to use provided time: " + str(v))
119-
kwargs[k] = dt.isoformat() + 'Z'
121+
iso_date = dt.isoformat()
122+
if not dt.tzinfo:
123+
# assume UTC for datetimes without an explicit timezone
124+
# necessary for RFC 3339 vs ISO 8601 compatability
125+
iso_date += 'Z'
126+
kwargs[k] = iso_date
120127
return _filter('DateRangeFilter', config=kwargs, field_name=field_name)
121128

122129

tests/test_filters.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import pytest
2+
from pytz import timezone
3+
from datetime import datetime
4+
from planet.api import filters
5+
6+
7+
@pytest.mark.parametrize('dt, expected', [
8+
(datetime(1900, 1, 1, tzinfo=timezone("US/Central")),
9+
{'field_name': 'acquired',
10+
'type': 'DateRangeFilter',
11+
'config': {'gte': '1900-01-01T00:00:00-05:51'}}),
12+
13+
(datetime(1999, 12, 31),
14+
{'field_name': 'acquired',
15+
'type': 'DateRangeFilter',
16+
'config': {'gte': '1999-12-31T00:00:00Z'}}),
17+
18+
("2018-01-01",
19+
{'field_name': 'acquired',
20+
'type': 'DateRangeFilter',
21+
'config': {'gte': '2018-01-01T00:00:00Z'}}),
22+
])
23+
def test_date_range(dt, expected):
24+
fieldname = "acquired"
25+
arg = "gte"
26+
27+
assert filters.date_range(fieldname, **{arg: dt}) == expected

0 commit comments

Comments
 (0)