Getting input date from the user in python using datetime.datetime

37,698

Solution 1

If you are using the %Y, %m, %d format, you can try with datetime.strptime:

from datetime import datetime

i = str(raw_input('date'))
try:
    dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
    print "Incorrect format"

Solution 2

datetime() only takes int as parameter.

Try this:

from datetime import datetime

date_entry = input('Enter a date (i.e. 2017,7,1)')
year, month, day = map(int, date_entry.split(','))
date = datetime(year, month, day)
Share:
37,698
Rob Stark
Author by

Rob Stark

Updated on July 05, 2022

Comments

  • Rob Stark
    Rob Stark almost 2 years

    I am trying to get input date from the user and store it in the form of

    dt_start = dt.datetime(2006, 1, 1)
    

    I am currently doing this:

    i = str(raw_input('date'))
    dt_start = dt.datetime(i)
    

    But it throws an error:

    Traceback (most recent call last):
    File "C:/.../sim.py", line 18, in <module>
        dt_start = dt.datetime(i)
    TypeError: an integer is required
    

    Thanks for the help guys!

    • Ryan O'Neill
      Ryan O'Neill about 11 years
      Are you expecting the user to enter "2006, 1, 1" as a string?
    • Rob Stark
      Rob Stark about 11 years
      After using the solution form @A.Rodas, I get this error:
    • Rob Stark
      Rob Stark about 11 years
      in <module> dt_start = dt.strptime(i, '%Y, %m, %d') AttributeError: 'module' object has no attribute 'strptime'
    • Ryan O'Neill
      Ryan O'Neill about 11 years
      Based on your example you need to use dt.datetime.strptime.