10000 New deseriailizer for date<iso_8601> · yikaraman/twilio-python@86c3ef0 · GitHub
[go: up one dir, main page]

Skip to content

Commit 86c3ef0

Browse files
author
matt
committed
New deseriailizer for date<iso_8601>
1 parent 31da20b commit 86c3ef0

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

tests/unit/rest/test_deserialize.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@
77
from twilio import deserialize
88

99

10+
class Iso8601DateTestCase(unittest.TestCase):
11+
12+
def test_parsable(self):
13+
actual = deserialize.iso8601_date('2015-01-02')
14+
expected = datetime.date(2015, 1, 2)
15+
self.assertEqual(expected, actual)
16+
17+
def test_not_parsable(self):
18+
actual = deserialize.iso8601_date('not-a-date')
19+
self.assertEqual('not-a-date', actual)
20+
21+
1022
class Iso8601DateTimeTestCase(unittest.TestCase):
1123

1224
def test_parsable(self):
@@ -15,8 +27,8 @@ def test_parsable(self):
1527
self.assertEqual(expected, actual)
1628

1729
def test_not_parsable(self):
18-
actual = deserialize.iso8601_datetime('not-a-date')
19-
self.assertEqual('not-a-date', actual)
30+
actual = deserialize.iso8601_datetime('not-a-datetime')
31+
self.assertEqual('not-a-datetime', actual)
2032

2133

2234
class DecimalTestCase(unittest.TestCase):

twilio/deserialize.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,32 @@
33
from email.utils import parsedate
44
import pytz
55

6+
ISO8601_DATE_FORMAT = '%Y-%m-%d'
7+
ISO8601_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
8+
9+
10+
def iso8601_date(s):
11+
"""
12+
Parses an ISO 8601 date string and returns a UTC date object or the string
13+
if the parsing failed.
14+
:param s: ISO 8601-formatted date string (2015-01-25)
15+
:return:
16+
"""
17+
try:
18+
return datetime.datetime.strptime(s, ISO8601_DATE_FORMAT).replace(tzinfo=pytz.utc).date()
19+
except ValueError:
20+
return s
21+
622

723
def iso8601_datetime(s):
824
"""
9-
Parses an ISO 8601 date string and returns a UTC datetime object,
25+
Parses an ISO 8601 datetime string and returns a UTC datetime object,
1026
or the string if parsing failed.
11-
:param s: ISO 8601-formatted string date
27+
:param s: ISO 8601-formatted datetime string (2015-01-25T12:34:56Z)
1228
:return: datetime or str
1329
"""
14-
format = "%Y-%m-%dT%H:%M:%SZ"
1530
try:
16-
return datetime.datetime.strptime(s, format).replace(tzinfo=pytz.utc)
31+
return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace(tzinfo=pytz.utc)
1732
except ValueError:
1833
return s
1934

0 commit comments

Comments
 (0)
0