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.

Lacer
  • 5,668
  • 10
  • 33
  • 45
  • possible duplicate of [Converting a string to a formatted date-time string using Python](http://stackoverflow.com/questions/2316987/converting-a-string-to-a-formatted-date-time-string-using-python) – TigerhawkT3 Jul 23 '15 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. – TigerhawkT3 Jul 23 '15 at 23:58
  • doing that gives me an invalid input. – Lacer Jul 24 '15 at 00: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). – TigerhawkT3 Jul 24 '15 at 00:12

1 Answers1

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
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97