Skip to content

Commit

Permalink
fix date-time parsing for strings without milliseconds
Browse files Browse the repository at this point in the history
  • Loading branch information
hjacobs committed Jul 23, 2015
1 parent bd3b074 commit 9966902
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 13 deletions.
14 changes: 1 addition & 13 deletions connexion/decorators/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
language governing permissions and limitations under the License.
"""

import datetime
import flask
import functools
import logging
import numbers
import types

from connexion.utils import parse_datetime
from connexion.problem import problem

logger = logging.getLogger('connexion.decorators.parameters')
Expand All @@ -30,18 +30,6 @@
'boolean': bool} # map of swagger types to python types


def parse_datetime(s: str):
'''http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14'''
try:
# "Z" for UTC
datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%fZ')
except:
# "+02:00" time zone offset
# remove the ":" first (%z expects "+0200")
x = s[:-3] + s[-2:]
datetime.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f%z')


FORMAT_MAP = {('string', 'date-time'): parse_datetime}


Expand Down
17 changes: 17 additions & 0 deletions connexion/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
language governing permissions and limitations under the License.
"""

import datetime
import importlib
import re

Expand Down Expand Up @@ -71,3 +72,19 @@ def produces_json(produces: list) -> bool:
# todo handle parameters
maintype, subtype = mimetype.split('/') # type: str, str
return maintype == 'application' and subtype.endswith('+json')


def parse_datetime(s: str):
'''http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14'''
if '.' not in s:
# hacked way of inserting the missing "time-secfrac" (milliseconds)
s1, sep, s2 = s.rpartition(':')
s = s1 + sep + s2[:2] + '.000' + s2[2:]
try:
# "Z" for UTC
datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%fZ')
except:
# "+02:00" time zone offset
# remove the ":" first (%z expects "+0200")
x = s[:-3] + s[-2:]
datetime.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f%z')
5 changes: 5 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,8 @@ def test_get_function_from_name():
function = utils.get_function_from_name('math.ceil')
assert function == math.ceil
assert function(2.7) == 3


def test_parse_datetime():
utils.parse_datetime('2015-05-05T01:01:01.001+02:00')
utils.parse_datetime('2015-05-05T01:01:01Z')

0 comments on commit 9966902

Please sign in to comment.