python - 在我的程序上下文中向日期时间输入添加异常处理的最简单方法是什么?
问题描述
我想在调用日期后立即验证日期的输入,以便用户不会输入所有三个,然后再次收到错误/日期提示,但我想不出办法做到这一点。我需要重组,还是有什么方法我错过了?
我有一个task
定义如下的类对象:
class task:
def __init__(self, name, due, category):
self.name = name
self.due = datetime.strptime(due, '%B %d %Y %I:%M%p')
self.category = category
def expand(self): # returns the contents of the task
return str(self.name) + " is due in " + str((self.due - datetime.now()))
该类是通过addTask
定义如下的函数创建的:
def addTask(name, due, category):
newTask = task(name, due, category)
data.append(newTask)
with open('./tasks.txt', 'wb') as file:
pickle.dump(data, file)
load_data()
list_tasks()
输入收集如下:
def ask():
while True:
arg = input("").lower()
if arg == "add":
addTask(input("What is the task? "),input("When's it due? "),input("What's the category? "))
elif arg =="help":
help()
elif arg =="list":
list_tasks()
else:
print("Command not recognized. Type 'help' for a list of commands.")
解决方案
一种方法是在将日期时间传递给addTask
try/except 块之前对其进行验证。
def ask():
while True:
arg = input("").lower()
if arg == "add":
task = input("What is the task? ")
due = input("When's it due? ")
category = input("What's the category? "))
try:
due = datetime.strptime(due, '%B %d %Y %I:%M%p')
except ValueError:
raise ValueError("Incorrect date format")
addTask(task, due, category)
elif arg =="help":
help()
elif arg =="list":
list_tasks()
else:
print("Command not recognized. Type 'help' for a list of commands.")
有更强大的验证方法,例如使用 Marshmallow 库,但这对于您正在处理的工作来说可能是多余的。
推荐阅读
- python-3.x - GCP - 获取有关存储桶的完整信息
- c# - 为什么它在正确后不继续插入表格?
- angular - ng-2 图表堆积条形图
- vb6 - 无法打开 VB6 项目 - actbar.ocx 和 dll 错误
- python - 如何合并同一数据框的多列
- excel - 如何使用“If”语句比较两个条件?
- python - 在 python 中捕获 HTTP 错误的响应正文
- node.js - 无法从 Express 服务器下载 Excel 文件
- php - 如何在php中构建一个自动路由器?
- android - Jsoup 在检查 hasAttribute 方法时抛出 NullPointerException (Android)