Datetime模块 - ValueError try / except将不起作用python 3

时间:2016-04-11 04:22:55

标签: python function datetime try-except

我有编程作业。一切顺利,直到我使用Try / Except遇到问题。如果我键入一个有效的日期时间,程序将接受它,它将继续,但如果我使用有效的日期时间格式,该异常将不会作出反应。

这是我的代码:

 import datetime
import csv


def get_stock_name(prompt,mode):
    while True:
        try:
            return open(input(prompt) + ".csv")
        except FileNotFoundError:
            print("File not found. Please try again.")
        except IOError:
            print("There was an IOError opening the file. Please try again.")


def get_stock_date(prompt):
    while True:
        try:
            return (input(prompt))
        except TypeError:
            print("Try again.")
        except ValueError:
            print("Try again.")


def get_stock_purchased(prompt):
    while True:
        try:
            return (input(prompt))
        except ValueError:
            print("Try again.")
        except TypeError:
            print("try again.")


stock_name = get_stock_name("Enter the name of the file ==> ", "w")

stock_date = datetime.datetime.strptime(get_stock_date("Enter the stock purchase date ==> " , "%m/%d/%Y"))

stock_sold = datetime.datetime.strptime(get_stock_date("Enter the date you sold the stock ==>" , "%m/%d/%Y"))

stock_purchased = get_stock_purchased("How many stocks were purchased on start date ==>")

1 个答案:

答案 0 :(得分:0)

你现在有一个循环会立即结束这个功能并在我能想到的任何情况下返回一个字符串,例外情况(如上所述)我认为不会发生,a使用错误数量的参数调用strptime,并使用错误数量的参数对函数进行递归调用。而且你永远不会保存或返回有意义的价值。也许递归调用只是有错误的缩进?无论如何,你必须完全重构你的代码,因为大多数代码都没有意义:

import datetime
def get_stock_date(prompt):
    while True:
        d = input(prompt)
        try:
            d = datetime.datetime.strptime(d, "%m/%d/%Y")
        except (ValueError, TypeError):
            print("Try again.")
        else:
            return d

stock_date = get_stock_date("Enter the stock purchase date ==> ")