Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make DateTime validator always return a datetime #66

Merged
merged 2 commits into from
Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion cleancat/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,16 @@ class DateTime(Regex):
regex = "^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$"
regex_message = 'Invalid ISO 8601 datetime.'
blank_value = None
_force_datetime: bool

def __init__(self, *args, **kwargs):
def __init__(self, *args, force_datetime: bool = False, **kwargs):
"""
Args:
force_datetime: If True, always return a datetime object, even if
the input does not specify a time.
"""
self.min_date = kwargs.pop('min_date', None)
self._force_datetime = force_datetime
super(DateTime, self).__init__(*args, **kwargs)

def clean(self, value):
Expand All @@ -217,6 +224,9 @@ def clean(self, value):
)
raise ValidationError(err_msg)

if self._force_datetime: # don't convert to a date
return dt

time_group = match.groups()[11]
if time_group and len(time_group) > 1:
return dt
Expand Down
10 changes: 10 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,16 @@ class TestDateTimeField:
def test_it_accepts_date_string(self):
assert DateTime().clean('2012-10-09') == datetime.date(2012, 10, 9)

def test_it_forces_datetime_resolution(self):
ret_dt = DateTime(force_datetime=True).clean("2012-10-09")
assert isinstance(ret_dt, datetime.datetime)
assert ret_dt == datetime.datetime(2012, 10, 9)

ret_date = DateTime(force_datetime=False).clean("2012-10-09")
assert isinstance(ret_date, datetime.date)
assert not isinstance(ret_date, datetime.datetime)
assert ret_date == datetime.date(2012, 10, 9)

def test_it_accepts_datetime_string(self):
expected = datetime.datetime(2012, 10, 9, 13, 10, 4)
assert DateTime().clean('2012-10-09 13:10:04') == expected
Expand Down