Lacer
Lacer

Reputation: 5968

python - convert date input to date output without time

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.

Upvotes: 0

Views: 1151

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49330

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

Upvotes: 1

Related Questions