Datetime module - ValueError try/except won't work python 3

核能气质少年 提交于 2019-12-02 14:24:09

To clarify Tigerhawk's initial comment: in order for the try-catch to handle TypeError or ValueError, you need to cast the input to datetime in the try statement.

import datetime

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

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

Additionally, your initial post had strange indentation that made it look like you were making a recursive call to get_stock_date, which caused confusion.

Lastly, you will need to use raw_input if you're using Python 2.

You currently have a loop that will immediately end the function and return a string in any situation I can think of off the top of my head, exceptions that (as just mentioned) I don't think will happen, a call to strptime with the wrong number of arguments, and a recursive call to your function with the wrong number of arguments. And you never save or return a meaningful value. Maybe the recursive call just has wrong indentation? Anyway, you'll have to completely restructure your code, as most of it makes little sense:

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 ==> ")

I think this is what you are looking for:

def get_stock_date(prompt):
    try:
        stock_date = datetime.datetime.strptime(prompt, "%m/%d/%Y")
        return(stock_date)
    except:
        print("Try Again.")
        prompt = input("Enter the stock purchase date ==> ")
        get_stock_date(prompt)

get_stock_date(input("Enter the stock purchase date ==> " ))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!