Skip to content

Commit

Permalink
[#50] handle invalid 8-digit date strings
Browse files Browse the repository at this point in the history
+ minor refactoring of typecast.date()
  • Loading branch information
aepyornis committed Dec 4, 2018
1 parent d883fd5 commit a800863
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/nycdb/typecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,14 @@ def mm_dd_yyyy(date_str):
# TODO: allow for different date inputs besides mm/dd/yyyy
# 03/04/2015 12:00:00 AM
def date(x):
if isinstance(x, datetime.date) or isinstance(x, datetime.datetime):
if isinstance(x, (datetime.date, datetime.datetime)):
return x

# checks for 20181231 date input
if re.match(r'[0-9]{8}', x):
date = datetime.datetime.strptime(x, '%Y%m%d')
return datetime.date(date.year, date.month, date.day)
try:
return datetime.datetime.strptime(x, '%Y%m%d').date()
except ValueError:
return None
# checks for 12/31/2018 date input
elif len(x) == 10 and len(x.split('/')) == 3:
return mm_dd_yyyy(x)
Expand Down
4 changes: 4 additions & 0 deletions src/tests/unit/test_typecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ def test_date_yyyymmdd_string():
assert typecast.date('19250501') == datetime.date(1925, 5, 1)


def test_date_invalid_yyyymmdd_string():
assert typecast.date('19940231') is None


def test_date_mm_dd_yyyy():
assert typecast.date('05/01/1925') == datetime.date(1925, 5, 1)

Expand Down

0 comments on commit a800863

Please sign in to comment.