PYTHON-759 - Fix ISO-8601 support for python 2.4 and 2.5

This commit is contained in:
Bernie Hackett 2014-09-18 10:10:50 -07:00
parent 9e7fd4865a
commit 69a08095d6
2 changed files with 12 additions and 3 deletions

View File

@ -80,6 +80,7 @@ import base64
import calendar
import datetime
import re
import time
json_lib = True
try:
@ -174,8 +175,12 @@ def object_hook(dct, compile_re=True):
dtm = dct["$date"]
# mongoexport 2.6 and newer
if isinstance(dtm, basestring):
aware = datetime.datetime.strptime(
dtm[:23], "%Y-%m-%dT%H:%M:%S.%f").replace(tzinfo=utc)
# datetime.datetime.strptime is new in python 2.5
naive = datetime.datetime(
*(time.strptime(dtm[:19], "%Y-%m-%dT%H:%M:%S")[0:6]))
# The %f format is new in python 2.6
micros = int(dtm[20:23]) * 1000
aware = naive.replace(microsecond=micros, tzinfo=utc)
offset = dtm[23:]
if not offset:
# No offset, assume UTC.

View File

@ -99,13 +99,17 @@ class TestJsonUtil(unittest.TestCase):
jsn = '{"dt": { "$date" : "1970-01-01T01:00:00.000+01:00"}}'
self.assertRaises(ValueError, json_util.loads, jsn)
dtm = datetime.datetime(1, 1, 1, 1, 1, 1, 0, utc)
jsn = '{"dt": {"$date": -62135593139000}}'
self.assertEqual(dtm, json_util.loads(jsn)["dt"])
jsn = '{"dt": {"$date": {"$numberLong": "-62135593139000"}}}'
self.assertEqual(dtm, json_util.loads(jsn)["dt"])
# Test support for microsecond accuracy
dtm = datetime.datetime(2014, 9, 17, 22, 41, 22, 201000, utc)
jsn = '{"dt": { "$date" : "2014-09-17T15:41:22.201-0700"}}'
self.assertEqual(dtm, json_util.loads(jsn)["dt"])
def test_regex_object_hook(self):
# simplejson or the builtin json module.
from bson.json_util import json