Skip to content

Commit 69a0809

Browse files
committed
PYTHON-759 - Fix ISO-8601 support for python 2.4 and 2.5
1 parent 9e7fd48 commit 69a0809

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

bson/json_util.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
import calendar
8181
import datetime
8282
import re
83+
import time
8384

8485
json_lib = True
8586
try:
@@ -174,8 +175,12 @@ def object_hook(dct, compile_re=True):
174175
dtm = dct["$date"]
175176
# mongoexport 2.6 and newer
176177
if isinstance(dtm, basestring):
177-
aware = datetime.datetime.strptime(
178-
dtm[:23], "%Y-%m-%dT%H:%M:%S.%f").replace(tzinfo=utc)
178+
# datetime.datetime.strptime is new in python 2.5
179+
naive = datetime.datetime(
180+
*(time.strptime(dtm[:19], "%Y-%m-%dT%H:%M:%S")[0:6]))
181+
# The %f format is new in python 2.6
182+
micros = int(dtm[20:23]) * 1000
183+
aware = naive.replace(microsecond=micros, tzinfo=utc)
179184
offset = dtm[23:]
180185
if not offset:
181186
# No offset, assume UTC.

test/test_json_util.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,17 @@ def test_datetime(self):
9999
jsn = '{"dt": { "$date" : "1970-01-01T01:00:00.000+01:00"}}'
100100
self.assertRaises(ValueError, json_util.loads, jsn)
101101

102-
103102
dtm = datetime.datetime(1, 1, 1, 1, 1, 1, 0, utc)
104103
jsn = '{"dt": {"$date": -62135593139000}}'
105104
self.assertEqual(dtm, json_util.loads(jsn)["dt"])
106105
jsn = '{"dt": {"$date": {"$numberLong": "-62135593139000"}}}'
107106
self.assertEqual(dtm, json_util.loads(jsn)["dt"])
108107

108+
# Test support for microsecond accuracy
109+
dtm = datetime.datetime(2014, 9, 17, 22, 41, 22, 201000, utc)
110+
jsn = '{"dt": { "$date" : "2014-09-17T15:41:22.201-0700"}}'
111+
self.assertEqual(dtm, json_util.loads(jsn)["dt"])
112+
109113
def test_regex_object_hook(self):
110114
# simplejson or the builtin json module.
111115
from bson.json_util import json

0 commit comments

Comments
 (0)