0

Input is: 2011-01-01 Output is: 2011-01-01 00:00:00

How do it get it to output to be: 2011-01-01 ??

# Packages
import datetime

def ObtainDate():
    global d
    isValid=False
    while not isValid:
        userInDate = raw_input("Type Date yyyy-mm-dd: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d = datetime.datetime.strptime(userInDate, '%Y-%m-%d')
            isValid=True
        except:
            print "Invalid Input. Please try again.\n"
    return d


print ObtainDate()

actually not the same as the reference. I'm asking just for the date not the time.

4
  • possible duplicate of Converting a string to a formatted date-time string using Python Commented Jul 23, 2015 at 23:47
  • You can format the output just like you formatted the input. Change a single letter (strptime to strftime) and you're 99% of the way there. Commented Jul 23, 2015 at 23:58
  • doing that gives me an invalid input. Commented Jul 24, 2015 at 0:00
  • Actually, you can just try the parse and, if successful, assign d = userInDate, since you just wanted to check whether the input was valid (added to answer). Commented Jul 24, 2015 at 0:12

1 Answer 1

1

Just format the parsed object with your desired formatting.

d = datetime.datetime.strftime(datetime.datetime.strptime(userInDate, '%Y-%m-%d'), '%Y-%m-%d')

 

>>> d
'2015-05-09'

...Actually, if you don't want to change the formatting at all, just do this:

try: # strptime throws an exception if the input doesn't match the pattern
    datetime.datetime.strptime(userInDate, '%Y-%m-%d')
except ValueError:
    print "Invalid Input. Please try again.\n"
else:
    isValid=True
    d = userInDate

In fact, you can skip datetime entirely if you want speed:

if userInDate.replace('-','').isdigit() and len(userInDate) == 10 and userInDate[4] == userInDate[7] == '-':
    d = userInDate
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.