Skip to content Skip to sidebar Skip to footer

Datetime - How To Require 2-digit Days And Months?

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 sensitiv

Solution 1:

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.

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}$")>>>defvalid_datestring(datestring):...if pattern.match(datestring):...returnTrue...returnFalse...>>>valid_datestring('1/1/2001')
False
>>>valid_datestring('01/01/2001')
True

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')

Solution 2:

You can verify that a string conforms exactly to a formatting string by re-formatting the datetime and comparing to the original string:

datetime_=datetime.strptime(datetime_string,DATETIME_FORMAT)ifdatetime_.strftime(DATETIME_FORMAT)!=datetime_string:
    [fail]

Post a Comment for "Datetime - How To Require 2-digit Days And Months?"