python - 将日期输入转换为日期输出,没有时间

时间:2015-07-23 23:46:21

标签: python datetime

输入为:2011-01-01 输出为:2011-01-01 00:00:00

如何将其输出为: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()

实际上与参考不一样。我只是问日期而不是时间。

1 个答案:

答案 0 :(得分:1)

只需使用所需的格式设置已解析对象的格式。

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

>>> d
'2015-05-09'

...实际上,如果您根本不想更改格式,请执行以下操作:

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

事实上,如果你想要速度,你可以完全跳过datetime

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