如何在python中验证日期 [英] how to validate a date in python

查看:93
本文介绍了如何在python中验证日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中验证一些日期。但问题是我的范围很广,例如,我的约会日期从 1/1/2014 2014/07/07 。所以我的问题是如何验证格式和值。我查看了此链接,但它仅验证格式,而不验证特定值。

hi i would like to validate some date in python. but the problem is that i have a praticular range, for example, my date goes from 1/1/2014to 08/07/2014 . So my question is how do i validate both the format and the value. i looked at this link but it only validates the format but not the specific values.

import time
date = input('Date (mm/dd/yyyy): ')enter date here
try:
    valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
    print('Invalid date!')

如何在Python 3.x中验证日期?

推荐答案

使用 time.strptime() > datetime.datetime.strptime(),然后验证结果对象是否在您的范围内:

Rather than use time.strptime(), use datetime.datetime.strptime() and then validate the resulting object to be within your range:

from datetime import datetime, date
date_input = input('Date (mm/dd/yyyy): ')
try:
    valid_date = datetime.strptime(date_input, '%m/%d/%Y').date()
    if not (date(2014, 1, 1) <= valid_date <= date(2014, 8, 7)):
        raise ValueError('Date out of range')
except ValueError:
    print('Invalid date!')

如果没有抛出异常, 有效日期绑定到 datetime.date()实例

If no exception is thrown, valid_date is bound to a datetime.date() instance.

这篇关于如何在python中验证日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆