为 Python argparse 输入参数指定日期格式 [英] Specify date format for Python argparse input arguments
问题描述
我有一个需要一些命令行输入的 Python 脚本,我正在使用 argparse
来解析它们.我发现文档有点混乱,找不到检查输入参数格式的方法.这个示例脚本解释了我检查格式的意思:
I have a Python script that requires some command line inputs and I am using argparse
for parsing them. I found the documentation a bit confusing and couldn't find a way to check for a format in the input parameters. What I mean by checking format is explained with this example script:
parser.add_argument('-s', "--startdate", help="The Start Date - format YYYY-MM-DD ", required=True)
parser.add_argument('-e', "--enddate", help="The End Date format YYYY-MM-DD (Inclusive)", required=True)
parser.add_argument('-a', "--accountid", type=int, help='Account ID for the account for which data is required (Default: 570)')
parser.add_argument('-o', "--outputpath", help='Directory where output needs to be stored (Default: ' + os.path.dirname(os.path.abspath(__file__)))
我需要检查选项 -s
和 -e
用户输入的格式为 YYYY-MM-DD
.argparse
中是否有我不知道的选项可以完成此操作?
I need to check for option -s
and -e
that the input by the user is in the format YYYY-MM-DD
. Is there an option in argparse
that I do not know of which accomplishes this?
推荐答案
Per 文档:
add_argument()
的 type
关键字参数允许执行任何必要的类型检查和类型转换...... type
的参数> 可以是任何接受单个字符串的可调用对象.
The
type
keyword argument ofadd_argument()
allows any necessary type-checking and type conversions to be performed ... The argument totype
can be any callable that accepts a single string.
你可以这样做:
def valid_date(s):
try:
return datetime.strptime(s, "%Y-%m-%d")
except ValueError:
msg = "not a valid date: {0!r}".format(s)
raise argparse.ArgumentTypeError(msg)
然后将其用作 type
:
parser.add_argument(
"-s",
"--startdate",
help="The Start Date - format YYYY-MM-DD",
required=True,
type=valid_date
)
这篇关于为 Python argparse 输入参数指定日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!