how do I take input in the date time format?

2019-03-04 19:42发布

问题:

I have written a code which take start_date and end_date from user but it is throwing an error.
Following is the code:

from datetime import datetime
start_date = datetime.strptime(input('Enter Start date in the format m/d/y'), '%m/%d/%Y')
end_date = datetime.strptime(input('Enter End date in the format m/d/y'), '%m/%d/%Y')
dates=['4/6/2013', '5/4/2013', '6/26/2013', '7/26/2013', '9/5/2013', '10/7/2013', '10/12/2013', '4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', '9/17/2014', '4/21/2015', '5/28/2015', '6/26/2015']

# this line creates a list of datetime objects from the given strings in list dates  

dt_dates = [datetime.strptime(date, '%m/%d/%Y') for date in dates]

in_between_dates = []
for d in dt_dates:
    if d >= start_date and d <= end_date:
        in_between_dates.append(d)

print [d.strftime('%m/%d/%Y') for d in in_between_dates]

and the error pops up after giving 1/1/2014 as input is as follows:

Enter Start date in the format m/d/y1/1/2014
Traceback (most recent call last):
  File "C:\Users\Ayush\Desktop\UWW Data Examples\new csvs\temp.py", line 9, in <module>
    start_date = datetime.strptime(input('Enter Start date in the format m/d/y'), '%m/%d/%Y')
TypeError: must be string, not int

回答1:

Since you are using print statement, seems like you are using Python 2.x .

In Python 2.x , input() actually evaluates the result and returns, so, if you are entering something like 1/1/2014 or some number, you would get an integer (which in this case is 1 divided by 1 divided by 2014 -> 0 ), not a string. And it is generally dangerous to use input() , since user can input anything and that would get evaluated.

Use raw_input() instead, to get the string, example -

start_date = datetime.strptime(raw_input('Enter Start date in the format m/d/y'), '%m/%d/%Y')
end_date = datetime.strptime(raw_input('Enter End date in the format m/d/y'), '%m/%d/%Y')

In Python 3.x , raw_input() from Python 2 was renamed to input() , so using input() in python 3 is same as using raw_input() in Python 2.x .



回答2:

For Python 2 use raw_input instead of input. For Python 3 input is fine.