Skip to content

Commit

Permalink
Merge pull request #99 from chrigrahcisco/master
Browse files Browse the repository at this point in the history
Added functionality to support microseconds for date-time validation
  • Loading branch information
jamesturk committed Jun 2, 2016
2 parents 8f449d6 + 037070c commit 023b5c2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 9 additions & 1 deletion validictory/tests/test_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,22 @@ class TestFormat(TestCase):
schema_spaces = {"format": "spaces"}
schema_non_empty_dict = {"type": "object", "format": "non-empty-dict"}

def test_format_datetime_pass(self):
def test_format_datetime_without_microseconds_pass(self):
data = "2011-01-13T10:56:53Z"

try:
validictory.validate(data, self.schema_datetime)
except ValueError as e:
self.fail("Unexpected failure: %s" % e)

def test_format_datetime_with_microseconds_pass(self):
data = "2011-01-13T10:56:53.0438Z"

try:
validictory.validate(data, self.schema_datetime)
except ValueError as e:
self.fail("Unexpected failure: %s" % e)

def test_format_date_pass(self):
data = "2011-01-13"

Expand Down
11 changes: 10 additions & 1 deletion validictory/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,16 @@ def __init__(self, errors):
def _generate_datetime_validator(format_option, dateformat_string):
def validate_format_datetime(validator, fieldname, value, format_option):
try:
datetime.strptime(value, dateformat_string)
# Additions to support date-time with microseconds without breaking existing date-time validation.
# Microseconds will appear specifically separated by a period, as some variable length decimal number
# such as '2015-11-18T19:57:05.061Z' instead of '2015-11-18T19:57:05Z' Better would be to use
# strict_rfc3339 vs datetime.strptime though the user needs the package installed for the import to succeed.
# import strict_rfc3339
# assert strict_rfc3339.validate_rfc3339(value)
if format_option == 'date-time' and '.' in value:
datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
else:
datetime.strptime(value, dateformat_string)
except:
msg = "is not in '{format_option}' format"
raise FieldValidationError(msg.format(format_option=format_option), fieldname, value)
Expand Down

0 comments on commit 023b5c2

Please sign in to comment.