datetime - python - convert date input to date output without time -


input is: 2011-01-01 output is: 2011-01-01 00:00:00

how output 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 exception if input doesn't match 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 same reference. i'm asking date not time.

just format parsed object desired formatting.

d = datetime.datetime.strftime(datetime.datetime.strptime(userindate, '%y-%m-%d'), '%y-%m-%d') 

 

>>> d '2015-05-09' 

...actually, if don't want change formatting @ all, this:

try: # strptime throws exception if input doesn't match pattern     datetime.datetime.strptime(userindate, '%y-%m-%d') except valueerror:     print "invalid input. please try again.\n" else:     isvalid=true     d = userindate 

in fact, can skip datetime entirely if want speed:

if userindate.replace('-','').isdigit() , len(userindate) == 10 , userindate[4] == userindate[7] == '-':     d = userindate 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -