python - how do I take input in the date time format? -
i have written code take start_date , end_date user throwing error.
following code:
from datetime import datetime start_date = datetime.strptime(input('enter start date in format m/d/y'), '%m/%d/%y') end_date = datetime.strptime(input('enter end date in 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'] # line creates list of datetime objects given strings in list dates dt_dates = [datetime.strptime(date, '%m/%d/%y') date in dates] in_between_dates = [] d in dt_dates: if d >= start_date , d <= end_date: in_between_dates.append(d) print [d.strftime('%m/%d/%y') d in in_between_dates] and error pops after giving 1/1/2014 input follows:
enter start date in 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 format m/d/y'), '%m/%d/%y') typeerror: must string, not int
since using print statement, seems using python 2.x .
in python 2.x , input() evaluates result , returns, so, if entering 1/1/2014 or number, integer (which in case 1 divided 1 divided 2014 -> 0 ), not string. , dangerous use input() , since user can input , evaluated.
use raw_input() instead, string, example -
start_date = datetime.strptime(raw_input('enter start date in format m/d/y'), '%m/%d/%y') end_date = datetime.strptime(raw_input('enter end date in format m/d/y'), '%m/%d/%y') in python 3.x , raw_input() python 2 renamed input() , using input() in python 3 same using raw_input() in python 2.x .
Comments
Post a Comment