当前位置: 动力学知识库 > 问答 > 编程问答 >

Error when inputting Date Python on Visual Studio 2015

问题描述:

I'm getting an error

must be string, not int

for these two lines of code.

userInput = input("Please enter your birthday (mm/dd/yyyy)")

birthday = datetime.datetime.strptime(userInput, '%m/%d/%Y').date()

The problem seems to be with variable userInput , but from the examples and tutorials I saw online, it should be working.

How to fix this error?

网友答案:

Change

userInput = input("Please enter your birthday (mm/dd/yyyy)")

to

userInput = raw_input("Please enter your birthday (mm/dd/yyyy)")

because the your original input is calculating the date as if it's carrying out a division.

EDIT: I don't use Visual Studio, but just in case, this is how I figured it out.

  1. The error is telling me that the userInput is returning an int instead of a string, so I checked it by running the code for userInput in a Python console.

  2. I checked what userInput collected:

    print userInput

  3. It returned 0, so I realized it was doing an integer division.

  4. I googled "python string user input" and it returned a link to StackOverflow, which was where I got the answer.

网友答案:

input handles user's input as code. So if you enter say, 25/09/2015, Python handles it as division of 25 by 9 and then by 2015. You can print userInput and see that it is 0. You have to input date in quotation marks (as string) or use raw_input.

BTW printing variables that seem to cause problems is a good debug method.

网友答案:

There seems to be some inconsistencies in Python 2.7 and Python 3 versions. I was using Python 2.7 while the tutorials I followed was using Python 3+, where input() works like it should in this case.

分享给朋友:
您可能感兴趣的文章:
随机阅读: