getting 2 different date input from user

Viewed 126

I am trying to get user input for 2 different dates which i will pass on to another function.

def twodifferentdates():
    print("Data between 2 different dates")
    start_date = datetime.strptime(input('Enter Start Date in m/d/y format'), '%m&d&Y')
    end_date = datetime.strptime(input('Enter end date in m/d/y format'), '%m&d&Y')
    print(start_date)

twodifferentdates()

I have tried a lot of different ways to enter the dates but i keep getting

ValueError: time data '01/11/1987' does not match format '%m&d&Y'

I have used the same code which was discussed in: how do I take input in the date time format?

Any help here would be appreciated.

3 Answers

Replace %m&d&Y with %m/%d/%Y as described in the referenced post.

datetime.strptime() requires you to specify the format, on a character-by-character basis, of the date you want to input. For the string '01/11/1987' you'd do

    datetime.strptime(..., '%m/%d/%Y')

where %m is "two-digit month", %d is "two-digit day" and %Y is "four-digit year" (as opposed to two-digit year %y. These values are separated by slashes.

See also the datetime documentation which describes how to use strptime and strftime.

I'm not very experienced with the datetime module, but the error seems to be the way you're taking input. You should be taking it like this:

start_date = datetime.strptime(input('Enter Start Date in m/d/y format'), '%m &d &Y')

or

start_date = datetime.strptime(input('Enter Start Date in m/d/y format'), '%m/&d/&Y')
Related