Skip to content

Commit 386ba08

Browse files
committed
Ensure microsecs are encoded when sending datetime objects to the API
1 parent 377995e commit 386ba08

1 file changed

Lines changed: 9 additions & 6 deletions

File tree

‎stream/serializer.py‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,18 @@
44

55
'''
66
Adds the ability to send date and datetime objects to the API
7+
Datetime objects will be encoded/ decoded with microseconds
78
The date and datetime formats from the API are automatically supported and parsed
89
'''
10+
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
11+
DATE_FORMAT = "%Y-%m-%d"
912

1013

1114
def _datetime_encoder(obj):
12-
if isinstance(obj, (datetime.datetime, datetime.date)):
13-
return obj.isoformat()
15+
if isinstance(obj, datetime.datetime):
16+
return datetime.datetime.strftime(obj, DATETIME_FORMAT)
17+
if isinstance(obj, datetime.date):
18+
return datetime.datetime.strftime(obj, DATE_FORMAT)
1419

1520

1621
def _datetime_decoder(dict_):
@@ -26,15 +31,13 @@ def _datetime_decoder(dict_):
2631
try:
2732
# The api always returns times like this
2833
# 2014-07-25T09:12:24.735
29-
datetime_obj = datetime.datetime.strptime(
30-
value, "%Y-%m-%dT%H:%M:%S.%f")
34+
datetime_obj = datetime.datetime.strptime(value, DATETIME_FORMAT)
3135
dict_[key] = datetime_obj
3236
except (ValueError, TypeError):
3337
try:
3438
# The api always returns times like this
3539
# 2014-07-25T09:12:24.735
36-
datetime_obj = datetime.datetime.strptime(
37-
value, "%Y-%m-%d")
40+
datetime_obj = datetime.datetime.strptime(value, DATE_FORMAT)
3841
dict_[key] = datetime_obj.date()
3942
except (ValueError, TypeError):
4043
continue

0 commit comments

Comments
 (0)