datetime-如何要求两位数的日期和月份? [英] datetime - how to require 2-digit days and months?

查看:431
本文介绍了datetime-如何要求两位数的日期和月份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用datetime模块对日期进行一些检查,以查看日期是采用mm / dd / yyyy还是mm / dd / yy格式。问题是%d和%m指令不够灵敏,无法检测到月或日是一位数字,这是我的要求。

I've been using the datetime module to do some checking of dates to see if they are in mm/dd/yyyy or mm/dd/yy formats. The problem is that the %d and %m directives aren't sensitive enough to detect when the month or day is a single digit, which is a requirement of mine.

datetime.strptime('01/01/2001', '%m/%d/%Y')

工作方式与我想要的一样,但是

works like I want it to, but

datetime.strptime('1/1/2001', '%m/%d/%Y')

也会产生有效的日期时间,当我真的希望它抛出ValueError时,除非将月份和日期填充为0。有谁知道如何为日期时间格式设置所需的精度?

also produces a valid datetime, when I really want it to throw a ValueError unless the month and day are 0-padded. Does anyone know how to set a required precision for datetime formats? Is this possible or should I just go with regex instead?

推荐答案

日期时间使用的函数并非旨在验证输入,仅用于将字符串转换为 datetime 对象。就 datetime 而言,这两个示例都是合法的字符串输入。

The datetime function you're using isn't intended to validate input, only to convert strings to datetime objects. Both of your examples are legitimate string inputs as far as datetime is concerned.

如果要强制执行用户输入为特定格式,我将使用正则表达式-从我的REPL中查看此示例:

If you want to enforce user input to be a specific format, I would go with a regex - see this example from my REPL:

>>> import re
>>> pattern = re.compile(r"^[0-9]{2}/[0-9]{2}/[0-9]{4}$")
>>> def valid_datestring(datestring):
...     if pattern.match(datestring):
...         return True
...     return False
...
>>> valid_datestring('1/1/2001')
False
>>> valid_datestring('01/01/2001')
True

如果要定义一个返回格式化日期或返回valueError的函数,您可以执行以下操作:

If you want to define a function that returns a formatted date or returns a valueError, you can do something like this:

def format_datestring(datestring):
    if not valid_datestring(datestring):
        raise ValueError('Date input must be in the form dd/mm/yyyy!')
    return datetime.strptime(datestring, '%m/%d/%Y')

这篇关于datetime-如何要求两位数的日期和月份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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