Rob Stark
Rob Stark

Reputation: 51

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

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!

Upvotes: 2

Views: 42820

Answers (2)

Johnny88520
Johnny88520

Reputation: 157

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)

Upvotes: 3

A. Rodas
A. Rodas

Reputation: 20679

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"

Upvotes: 9

Related Questions