Browse Source

Parse datetimes without microseconds

Datetimes without microseconds could not be parsed by utils.parse_datetime.
This update resolves that. It also allows milliseconds to be parsed correctly.

This was reported in #36.

Signed-off-by: Stan Janssen <stan.janssen@elaad.nl>
Stan Janssen 4 years ago
parent
commit
738f9990ab
2 changed files with 26 additions and 1 deletions
  1. 9 1
      openleadr/utils.py
  2. 17 0
      test/test_utils.py

+ 9 - 1
openleadr/utils.py

@@ -256,7 +256,15 @@ def parse_datetime(value):
     """
     """
     matches = re.match(r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.?(\d{1,6})?\d*Z', value)
     matches = re.match(r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.?(\d{1,6})?\d*Z', value)
     if matches:
     if matches:
-        year, month, day, hour, minute, second, micro = (int(value) for value in matches.groups())
+        year, month, day, hour, minute, second = (int(value)for value in matches.groups()[:-1])
+        micro = matches.groups()[-1]
+        if micro is None:
+            micro = 0
+        else:
+            if len(micro) == 6:
+                micro = int(micro)
+            else:
+                micro = int(micro + "0" * (6 - len(micro)))
         return datetime(year, month, day, hour, minute, second, micro, tzinfo=timezone.utc)
         return datetime(year, month, day, hour, minute, second, micro, tzinfo=timezone.utc)
     else:
     else:
         logger.warning(f"parse_datetime: {value} did not match format")
         logger.warning(f"parse_datetime: {value} did not match format")

+ 17 - 0
test/test_utils.py

@@ -284,3 +284,20 @@ def test_parse_duration():
     with pytest.raises(ValueError) as err:
     with pytest.raises(ValueError) as err:
         utils.parse_duration("Hello")
         utils.parse_duration("Hello")
     assert str(err.value) == f"The duration 'Hello' did not match the requested format"
     assert str(err.value) == f"The duration 'Hello' did not match the requested format"
+
+
+def test_parse_datetime_no_microseconds():
+    dt = "2020-12-15T11:29:34Z"
+    result = utils.parse_datetime(dt)
+    assert result == datetime(2020, 12, 15, 11, 29, 34, tzinfo=timezone.utc)
+
+def test_parse_datetime_with_microseconds():
+    dt = "2020-12-15T11:29:34.123456Z"
+    result = utils.parse_datetime(dt)
+    assert result == datetime(2020, 12, 15, 11, 29, 34, 123456, tzinfo=timezone.utc)
+
+
+def test_parse_datetime_with_milliseconds():
+    dt = "2020-12-15T11:29:34.123Z"
+    result = utils.parse_datetime(dt)
+    assert result == datetime(2020, 12, 15, 11, 29, 34, 123000, tzinfo=timezone.utc)