gpt4 book ai didi

python 验证日期格式或空白

转载 作者:太空宇宙 更新时间:2023-11-03 18:36:48 25 4
gpt4 key购买 nike

我正在尝试有效的用户输入。我有不止一种有效日期,其中一种是空白的。可能有一种简单的方法可以检查这一点,但我无法弄清楚。

def check_input(i):
valids = ['%Y-%m-%d', '%Y%M', '']
while True:
try:
date = strptime(i, valids)
except ValueError as e:
print 'Could not parse: {}'. format(e)
else:
return True

我认为我无法将列表传递给 strptime 对象。它返回 TypeError: unhashable type: 'list'.

这是脚本的片段

def parse_arguments():
parser = argparse.ArgumentParser(description='API Statistics')
parser.add_argument('-c', '--company', help='Company name')
parser.add_argument('-d', '--download', help='Download file', action='store_true')
return parser.parse_args()

def list_cmds(company):
for num, cmd in enumerate(company._cmds):
print '{}: {}'.format(num, cmd)

def get_cmd_dict(company):
return dict(enumerate(company._cmds))

def run_cmd(i, cmd, **kwargs):
return getattr(i, get_cmd_dict(i)[int(cmd)])(**kwargs)

def writer(data, file):
with open(file, 'w') as f:
f.write(data)

def get_func_args(f):
ins = inspect.getargspec(f).args
ins.remove('self')
return ins

def check_input(i):
valids = ['%Y-%m-%d', '%Y%M', '']
while True:
try:
date = strptime(i, valids)
except ValueError as e:
print 'Could not parse: {}'. format(e)
else:
return True

def main():
args = parse_arguments()

if args.company == 'parklogic':
i = PlAPI(11111, 'asdf', 'program', debug=False)
pl_cmds = get_cmd_dict(i)


print 'please select a command'
print '-----------------------'

list_cmds(PlAPI)

user_cmd = raw_input('Number: ')
print ''

cmd_args = get_func_args(getattr(i, pl_cmds[int(user_cmd)]))
users_args = {}
format_mapper = {0: 'YYYY-MM-DD',
1: 'YYYY-MM-DD',
2: 'YYYY-MM-DD',
3: 'YYYY-MM-DD',
4: 'YYYYMM',
5: 'YYYY-MM-DD',
6: 'YYYY-MM-DD HH:mm:ss',
7: 'YYYY-MM-DD',
8: 'YYYY-MM-DD'}

for arg in cmd_args:
user_input = raw_input('Enter {} as {} or leave blank: '.format(
arg, format_mapper[int(user_cmd)]))
if check_input(user_input):
users_args[arg] = user_input

resp = run_cmd(i, user_cmd, **users_args)

if args.download:
writer(resp.read(), '{}.csv'.format(pl_cmds[int(user_cmd)]))
else:
print resp.read()

if __name__ == '__main__':
main()

最佳答案

def check_input(i):
valids = ['%Y-%m-%d', '%Y%M', '']
for valid in valids
try:
return strptime(i, valid)
except ValueError as e:
pass
return False

关于python 验证日期格式或空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21415081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com