Validations are very important for any application because they make sure that the data entered by the user is valid. In this article, we will see how to validate the date string format using Python.

There are many way to do that in python. Following are some of the most common date string validation techniques.

Regular expressions

In Python, regular expressions are a powerful tool for validating date string formats. A regular expression is a character sequence that defines a search pattern. It is capable of searching, matching, and manipulating text. Python’s re module includes support for regular expressions.

Following is the example:

import re

date_regex = re.compile(r'^\d{4}-\d{2}-\d{2}$')

date_string = '2022-02-15'

if date_regex.match(date_string):
    print('Valid date string')
else:
    print('Invalid date string')

In the above example, we created a regular expression pattern that matches strings with the format ‘YYYY-MM-DD‘.

  • The pattern uses the ^ and $ characters to denote the start and end of the string.
  • The \d character matches any digit.
  • {n} syntax specifies the number of digits to match.

The match function whether the date_string matches the date_regex pattern. If it does, it prints ‘Valid date string’. If it does not, it prints ‘Invalid date string’.

Datetime module:

With the python datetime module, the date format strings can be parsed into datetime object. The strptime() method allows us to specify the date string format and returns a datetime object. If the date string format is invalid, a ValueError exception is raised.

Following is an example:

from datetime import datetime

date_string = '2022-02-15'

try:
    datetime.strptime(date_string, '%Y-%m-%d')
    print('Valid date string')
except ValueError:
    print('Invalid date string')

In the above example, we use the strptime() method to parse the date_string into a datetime object. The second argument to strptime() specifies the expected date string format.

If the date string format is invalid, a ValueError exception is raised. We used try & except block to handle this exception and print ‘Invalid date string‘.

Dateutil

With the dateutil module we can parse date strings into datetime objects.

However, with the above two methods we can validate the datetime with any given format but with the dateutils’s parser.parse() method we can parse a wide variety of date formats and returns a datetime object.

The parse() method throws a ValueError exception if the date string format is invalid. This needs to be handled in the except block.

from dateutil import parser

date_string = '2022-02-15'

try:
    parser.parse(date_string)
    print('Valid date string')
except ValueError:
    print('Invalid date string')

Categorized in:

Tagged in: