I'm currently building a command line interface in Python 3 with the argparse
module.
I have a situation where I need to define choices (e.g. "today", "yesterday", "week"
, ...) for an optional argparse
argument -s
of a subparser, but also allow a date string, but only if it can be successfully parsed as datetime.datetime
with a predefined format (e.g. "%Y-%m-%d"), otherwise an exception would be raise
d.
parser.add_argument(
"-s",
"--start-date",
type=str,
default="today",
choices=["today", "yesterday", "week", <date>], # date should be accepted only if datetime.strptime(date, "%Y-%m-%d") is successful
help="start date help",
)
Is this somehow possible?