Update requirements to include kazoo
[python_utils.git] / string_utils.py
index 4127079fc0a1b5670e676986421fad26009a3733..24fc59542ba96614e364c0331d9db738258bfa32 100644 (file)
@@ -1388,6 +1388,43 @@ def to_date(in_str: str) -> Optional[datetime.date]:
     return None
 
 
+def extract_date(in_str: Any) -> Optional[datetime.datetime]:
+    """Finds and extracts a date from the string, if possible.
+
+    Args:
+        in_str: the string to extract a date from
+
+    Returns:
+        a datetime if date was found, otherwise None
+
+    >>> extract_date("filename.txt    dec 13, 2022")
+    datetime.datetime(2022, 12, 13, 0, 0)
+
+    >>> extract_date("Dear Santa, please get me a pony.")
+
+    """
+    import itertools
+
+    import dateparse.dateparse_utils as du
+
+    d = du.DateParser()  # type: ignore
+    chunks = in_str.split()
+    for ngram in itertools.chain(
+        list_utils.ngrams(chunks, 5),
+        list_utils.ngrams(chunks, 4),
+        list_utils.ngrams(chunks, 3),
+        list_utils.ngrams(chunks, 2),
+    ):
+        try:
+            expr = " ".join(ngram)
+            logger.debug(f"Trying {expr}")
+            if d.parse(expr):
+                return d.get_datetime()
+        except du.ParseException:  # type: ignore
+            pass
+    return None
+
+
 def is_valid_date(in_str: str) -> bool:
     """
     Args: