我正在构建一种日历Web应用程序
我已经在HTML中设置了以下表格
1
2
3
4
5
6
7
8
Year ("yyyy"):
Month ("mm"):
Day ("dd"):
Hour ("hh"):
Description:
然后,来自用户的输入将被提交到小服务器中
我想知道,有没有办法检查用户输入的日期是否是有效日期?
显然,我可以编写很多if语句,但是是否有任何内置函数可以检查此内容?
谢谢
相关:如何验证python中的日期字符串格式?
您可以尝试使用datetime并处理异常以确定有效/无效日期:
范例:http://codepad.org/XRSYeIJJ
1
2
3
4
5
6
7
8import datetime
correctDate = None
try:
newDate = datetime.datetime(2008,11,42)
correctDate = True
except ValueError:
correctDate = False
print(str(correctDate))
你可以尝试做
1
2import datetime
datetime.datetime(year=year,month=month,day=day,hour=hour)
这将消除诸如> 12,小时> 23,不存在的leap日等问题(在非month年,month = 2的最大值为28,否则为29,其他月份的最大值为30或31天)(错误时引发ValueError异常)
您也可以尝试将其与一些合理的上限/下限进行比较。
例如:
1datetime.date(year=2000, month=1,day=1) < datetime.datetime(year=year,month=month,day=day,hour=hour) <= datetime.datetime.now()
相关的上限和下限取决于您的需求。
编辑:请记住,这不会处理某些日期时间的事情,这些事情可能对您的应用程序无效(最小生日,节假日,营业时间以外的时间等)。
使用datetime
例如。
1
2
3
4
5
6
7
8
9>>> from datetime import datetime
>>> print datetime(2008,12,2)
2008-12-02 00:00:00
>>> print datetime(2008,13,2)
Traceback (most recent call last):
File"", line 1, in
print datetime(2008,13,2)
ValueError: month must be in 1..12
但是那不会给我一个错误信息吗? 并导致一切都崩溃? 我希望有一个函数,例如,如果其有效日期返回1,如果无效,则返回0。 然后,我可以提示用户将日期重新输入到网页中。
或者您可以try...except并捕获错误。 然后,您可以执行所需的操作,如果愿意,可以静默传递错误。
该问题假定不带库的解决方案涉及"大量的if语句",但不包括:
1
2
3
4
5def 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])
您可以尝试使用datetime并处理异常以确定有效/无效日期:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import 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)))
给
1
2
3
4
5False
True
False
True
False
这是DhruvPathak的答案的改进,从编辑角度讲更有意义,但被拒绝,因为"此编辑旨在针对帖子的作者,没有任何意义。应将其写为评论或回答。"
这是使用时间的解决方案。
1
2
3
4
5
6
7
8
9import 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
您为什么要这样做,而不只是date(year, month, day)?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23y = 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("")
else:
print("")
elif m == 2: # But if it's not"Leap" year February will have 28 days
if d < 29:
print("")
else:
print("")
elif y % 4 != 0 and m != 2: # Otherwise print"Correct"
print("")
else:
print("")
更好地提供一些解释
尽管这可以回答作者的问题,但它缺少一些解释性的文字和文档链接。 没有一些短语,原始代码片段不是很有帮助。 您可能还会发现如何写一个好的答案很有帮助。 请修改您的答案。
因此,这是我的hacky解决方案,可纠正提供的无效日期。假定用户正在从通用html表单提交,该表单提供了1-31天作为选项。主要问题是用户提供当月不存在的一天(例如9月31日)
1
2
3
4
5
6
7
8
9
10
11
12
13def sane_date(year, month, day):
# Calculate the last date of the given month
nextmonth = datetime.date(year, month, 1) + datetime.timedelta(days=35)
lastday = nextmonth.replace(day=1) - datetime.timedelta(days=1)
return datetime.date(year, month, min(day, lastday.day))
class tests(unittest.TestCase):
def test_sane_date(self):
""" Test our sane_date() method"""
self.assertEquals(sane_date(2000,9,31), datetime.date(2000,9,30))
self.assertEquals(sane_date(2000,2,31), datetime.date(2000,2,29))
self.assertEquals(sane_date(2000,1,15), datetime.date(2000,1,15))