Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何检查日期是否有效?_Python_Validation_Date_Time - Fatal编程技术网

在python中,如何检查日期是否有效?

在python中,如何检查日期是否有效?,python,validation,date,time,Python,Validation,Date,Time,我正在构建一种日历web应用程序 我已经用HTML设置了以下表单 <form action='/event' method='post'> Year ("yyyy"): <input type='text' name='year' /> Month ("mm"): <input type='text' name='month' /> Day ("dd"): <input type='text' name='day' /> Hour ("hh"

我正在构建一种日历web应用程序

我已经用HTML设置了以下表单

<form action='/event' method='post'>
Year ("yyyy"):  <input type='text' name='year' />
Month ("mm"):  <input type='text' name='month' />
Day ("dd"):  <input type='text' name='day' />
Hour ("hh"):  <input type='text' name='hour' />
Description:  <input type='text' name='info' />
             <input type='submit' name='submit' value='Submit'/>
</form>

年份(“yyyy”):
月份(“mm”):
日期(“dd”):
小时数:
说明:
然后将用户的输入提交到cherrypy服务器中

我想知道,有没有办法检查用户输入的日期是否有效

显然,我可以编写大量的if语句,但是否有任何内置函数可以检查这一点


谢谢

使用
datetime

例如

>>从datetime导入datetime
>>>打印日期时间(2008,12,2)
2008-12-02 00:00:00
>>>打印日期时间(2008,13,2)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
打印日期时间(2008,13,2)
ValueError:月份必须在1..12之内
您可以尝试

import datetime
datetime.datetime(year=year,month=month,day=day,hour=hour)
这将消除一些情况,如月份>12、小时>23、不存在的闰日(月份=2在非闰年最多28天,否则为29,其他月份最多30或31天)(出错时抛出ValueError异常)

您还可以尝试将其与一些合理的上/下限进行比较。 例:


datetime.date(year=2000,month=1,day=1)

所以,这里是我的黑客解决方案,以纠正提供的无效日期。这假设用户是从提供第1-31天选项的通用html表单提交的。主要问题是用户提供的日期在该月不存在(9月31日除外)

def sane_日期(年、月、日):
#计算给定月份的最后日期
nextmonth=datetime.date(年、月、1)+datetime.timedelta(天=35)
lastday=nextmonth.replace(day=1)-datetime.timedelta(days=1)
返回日期time.date(年、月、分钟(天、最后一天、天))
类测试(unittest.TestCase):
def测试正常日期(自):
“”“测试我们的sane_date()方法”“”
自评资产质量(sane_日期(2000,9,31),datetime日期(2000,9,30))
自评资产质量(sane_日期(2000,2,31),datetime日期(2000,2,29))
自评资产质量(sane_日期(2000,1,15),datetime日期(2000,1,15))

以下是一个使用时间的解决方案

import time def is_date_valid(year, month, day): this_date = '%d/%d/%d' % (month, day, year) try: time.strptime(this_date, '%m/%d/%Y') except ValueError: return False else: return True 导入时间 def是否有效(年、月、日): 此日期=“%d/%d/%d%”(月、日、年) 尝试: time.strtime(此日期为“%m/%d/%Y”) 除值错误外: 返回错误 其他: 返回真值
您可以尝试使用datetime并处理异常以确定有效/无效日期:

import datetime

def check_date(year, month, day):
    correctDate = None
    try:
        newDate = datetime.datetime(year, month, day)
        correctDate = True
    except ValueError:
        correctDate = False
    return correctDate

#handles obvious problems
print(str(check_date(2008,11,42)))

#handles leap days
print(str(check_date(2016,2,29)))
print(str(check_date(2017,2,29)))

#handles also standard month length
print(str(check_date(2016,3,31)))
print(str(check_date(2016,4,31)))



这是一种改进,作为编辑更具意义,但被拒绝为“”

问题假设没有库的解决方案涉及“大量if语句”,但它没有:

def is_valid_date(year, month, day):
    day_count_for_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if year%4==0 and (year%100 != 0 or year%400==0):
        day_count_for_month[2] = 29
    return (1 <= month <= 12 and 1 <= day <= day_count_for_month[month])
def为有效日期(年、月、日):
月份的天数=[0,31,28,31,30,31,30,30,31,31,30,31,31,31,31]
如果第%4年==0且(第%100!=0年或第%400年==0年):
月[2]的日计数=29
返回(1
y=int(输入(“年:”)
m=int(输入(“月份:”)
d=整数(输入(“日:”)

如果0,您可以尝试使用
dateutil.parser
模块来简化日期解析:

from dateutil.parser import parse
def is_valid_date(date):
    if date:
        try:
            parse(date)
            return True
        except:
            return False
    return False

希望这能有所帮助。

但这不会给我一条错误消息吗?并导致一切崩溃吗?我希望有一个函数,例如,如果它是有效日期,返回1,如果它是无效日期,返回0。然后我可以提示用户在网页中重新输入日期。或者你可以
尝试…除了
并捕获错误。然后你可以做你想做的事,如果你愿意,可以默默地传递错误。相关:你为什么要这样做而不仅仅是
date(年、月、日)
?最好提供一些解释虽然这可能会回答作者的问题,但它缺少一些解释词和文档链接。如果没有一些短语,原始代码片段不会有很大帮助。您也可能会发现非常有帮助。请编辑您的答案。
import datetime

def check_date(year, month, day):
    correctDate = None
    try:
        newDate = datetime.datetime(year, month, day)
        correctDate = True
    except ValueError:
        correctDate = False
    return correctDate

#handles obvious problems
print(str(check_date(2008,11,42)))

#handles leap days
print(str(check_date(2016,2,29)))
print(str(check_date(2017,2,29)))

#handles also standard month length
print(str(check_date(2016,3,31)))
print(str(check_date(2016,4,31)))
False
True
False
True
False
def is_valid_date(year, month, day):
    day_count_for_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if year%4==0 and (year%100 != 0 or year%400==0):
        day_count_for_month[2] = 29
    return (1 <= month <= 12 and 1 <= day <= day_count_for_month[month])
y = int(input("Year: "))
m = int(input("Month: "))
d = int(input("Day: "))

if 0 <= y and 0 < m < 13 and 0 < d < 32: #Check whether date is under limit.

    if y % 4 == 0: # Every 4 year "Leap" year occures so checking...
        if m == 2: # In "Leap" year February has 29 days
            if d < 30:
                print("<Correct>")
            else:
                print("<Wrong>")

    elif m == 2: # But if it's not "Leap" year February will have 28 days
        if d < 29:
            print("<Correct>")
        else:
            print("<Wrong>")
    elif y % 4 != 0 and m != 2: # Otherwise print "Correct"
        print("<Correct>")

else:
    print("<Wrong>")
from dateutil.parser import parse
def is_valid_date(date):
    if date:
        try:
            parse(date)
            return True
        except:
            return False
    return False