指定Python argparse输入参数的日期格式 [英] Specify date format for Python argparse input arguments

查看:49
本文介绍了指定Python argparse输入参数的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

推荐答案

文档:

add_argument() type 关键字参数允许执行任何必要的类型检查和类型转换... type = 可以接受任何带有单个字符串参数并返回转换后值的可调用对象

The type keyword argument of add_argument() allows any necessary type-checking and type conversions to be performed ... type= can take any callable that takes a single string argument and returns the converted value

您可以执行以下操作:

def valid_date(s):
    try:
        return datetime.strptime(s, "%Y-%m-%d")
    except ValueError:
        msg = "Not a valid date: '{0}'.".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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆