From 80c9657c7f4d12e1d10e0e93bf1a4d26e72b4041 Mon Sep 17 00:00:00 2001 From: chfw Date: Wed, 23 Sep 2015 20:27:24 +0100 Subject: [PATCH] fix #3: accept long date time string 2015-08-17T19:09:59.999999 --- pyexcel_ods/__init__.py | 22 +++++++++++++--------- tests/test_bug_fixes.py | 29 +++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/pyexcel_ods/__init__.py b/pyexcel_ods/__init__.py index 8fbd7bc..ae9a7b4 100644 --- a/pyexcel_ods/__init__.py +++ b/pyexcel_ods/__init__.py @@ -34,7 +34,6 @@ load_data as read_data, store_data as write_data ) -import datetime import odf.opendocument from odf.table import TableRow, TableCell, Table from odf.text import P @@ -50,14 +49,19 @@ def float_value(value): def date_value(value): - if len(value) == 10: - ret = datetime.datetime.strptime(value, "%Y-%m-%d") - ret = ret.date() - elif len(value) == 19: - ret = datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S") - else: - raise Exception("Bad date format") - return ret + try: + if len(value) == 10: + ret = datetime.datetime.strptime(value, "%Y-%m-%d") + ret = ret.date() + elif len(value) == 19: + ret = datetime.datetime.strptime(value, "%Y-%m-%dT%H:%M:%S") + elif len(value) > 19: + ret = datetime.datetime.strptime(value[0:26], "%Y-%m-%dT%H:%M:%S.%f") + else: + raise Exception("Bad date value %s" % value) + return ret + except: + raise Exception("Bad date value %s" % value) def ods_date_value(value): diff --git a/tests/test_bug_fixes.py b/tests/test_bug_fixes.py index efadc3c..409c0e4 100644 --- a/tests/test_bug_fixes.py +++ b/tests/test_bug_fixes.py @@ -25,9 +25,34 @@ def test_date_util_parse(): value = "2015-08-17" d = date_value(value) assert d.strftime("%Y-%m-%d") == "2015-08-17" - + value = "2015-08-17T19:20:59.999999" + d = date_value(value) + assert d.strftime("%Y-%m-%dT%H:%M:%S") == "2015-08-17T19:20:59" + value = "2015-08-17T19:20:59.99999" + d = date_value(value) + assert d.strftime("%Y-%m-%dT%H:%M:%S") == "2015-08-17T19:20:59" + value = "2015-08-17T19:20:59.999999999999999" + d = date_value(value) + assert d.strftime("%Y-%m-%dT%H:%M:%S") == "2015-08-17T19:20:59" + @raises(Exception) def test_invalid_date(): from pyexcel_ods import date_value value = "2015-08-" - date_value(value) \ No newline at end of file + date_value(value) + +@raises(Exception) +def test_fake_date_time_10(): + from pyexcel_ods import date_value + date_value("1234567890") + +@raises(Exception) +def test_fake_date_time_19(): + from pyexcel_ods import date_value + date_value("1234567890123456789") + +@raises(Exception) +def test_fake_date_time_20(): + from pyexcel_ods import date_value + date_value("12345678901234567890") + \ No newline at end of file