From 5e1bced276766fec9d4c408790c99d4a26d267e0 Mon Sep 17 00:00:00 2001 From: Scott Gasch Date: Wed, 22 Sep 2021 17:37:17 -0700 Subject: Various little changes. Naming. Durations as arguments. --- argparse_utils.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'argparse_utils.py') diff --git a/argparse_utils.py b/argparse_utils.py index 0ee2be9..2d2297c 100644 --- a/argparse_utils.py +++ b/argparse_utils.py @@ -232,6 +232,28 @@ def valid_datetime(txt: str) -> datetime.datetime: 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(seconds=0) + + """ + from datetime_utils import parse_duration + try: + secs = parse_duration(txt) + except Exception as e: + raise argparse.ArgumentTypeError(e) + finally: + return datetime.timedelta(seconds=secs) + + if __name__ == '__main__': import doctest doctest.ELLIPSIS_MARKER = '-ANYTHING-' -- cgit v1.3