+
+
+def valid_datetime(txt: str) -> datetime.datetime:
+ """If the string is a valid datetime, return it. Otherwise raise
+ an ArgumentTypeError.
+
+ >>> valid_datetime('6/5/2021 3:01:02')
+ datetime.datetime(2021, 6, 5, 3, 1, 2)
+
+ # Again, these types of expressions work fine but are
+ # difficult to test with doctests because the answer is
+ # relative to the time the doctest is executed.
+ >>> valid_datetime('next christmas at 4:15am') # doctest: +ELLIPSIS
+ -ANYTHING-
+ """
+ from string_utils import to_datetime
+
+ dt = to_datetime(txt)
+ if dt is not None:
+ return dt
+ msg = f'Cannot parse argument as datetime: {txt}'
+ logger.error(msg)
+ raise argparse.ArgumentTypeError(msg)
+
+
+def valid_duration(txt: str) -> datetime.timedelta:
+ """If the string is a valid time duration, return a
+ datetime.timedelta representing the period of time. Otherwise
+ maybe raise an ArgumentTypeError or potentially just treat the
+ time window as zero in length.
+
+ >>> valid_duration('3m')
+ datetime.timedelta(seconds=180)
+
+ >>> valid_duration('your mom')
+ datetime.timedelta(0)
+
+ """
+ from datetime_utils import parse_duration
+
+ try:
+ secs = parse_duration(txt)
+ return datetime.timedelta(seconds=secs)
+ except Exception as e:
+ logger.exception(e)
+ raise argparse.ArgumentTypeError(e) from e
+
+
+if __name__ == '__main__':
+ import doctest
+
+ doctest.ELLIPSIS_MARKER = '-ANYTHING-'
+ doctest.testmod()