From 69a08095d69c8bbe4ed7ed328c8ff704127b315f Mon Sep 17 00:00:00 2001 From: Bernie Hackett Date: Thu, 18 Sep 2014 10:10:50 -0700 Subject: [PATCH] PYTHON-759 - Fix ISO-8601 support for python 2.4 and 2.5 --- bson/json_util.py | 9 +++++++-- test/test_json_util.py | 6 +++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/bson/json_util.py b/bson/json_util.py index ae63c7ee0..983573edc 100644 --- a/bson/json_util.py +++ b/bson/json_util.py @@ -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. diff --git a/test/test_json_util.py b/test/test_json_util.py index 60bdf0ac7..861cf02d0 100644 --- a/test/test_json_util.py +++ b/test/test_json_util.py @@ -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