python将日期输入转换为不带tim的日期输出

2024-09-27 07:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

输入为: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()

实际上和参考文献不一样。我只是问日期,不是时间。在


Tags: theimportfalseinputdatetimepackagesdefglobal
1条回答
网友
1楼 · 发布于 2024-09-27 07:28:01

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

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

^{pr2}$

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

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

相关问题 更多 >

    热门问题