Computer >> Computer tutorials >  >> Programming >> Python

How to do date validation in Python?


The date validation you want to achieve in python will largely depend on the format of the date you have. The strptime function from the datetime library can be used to parse strings to dates/times.

Example

import datetime
date_string = '2017-12-31'
date_format = '%Y-%m-%d'
try:
  date_obj = datetime.datetime.strptime(date_string, date_format)
  print(date_obj)
except ValueError:
  print("Incorrect data format, should be YYYY-MM-DD")

Output

This will give the output −

2017-12-31 00:00:00

You can use many other directives to parse the date. Following are the directives supported by strptime()'s format string.

Directive    
Meaning
%a
Locale's abbreviated weekday name.
%A
Locale's full weekday name.    
%b
Locale's abbreviated month name.  
%B
Locale's full month name.
%c
Locale's appropriate date and time representation.    
%d
Day of the month as a decimal number [01,31].
%H
Hour (24-hour clock) as a decimal number [00,23].
%I
Hour (12-hour clock) as a decimal number [01,12].        
%j
Day of the year as a decimal number [001,366].
%m
Month as a decimal number [01,12].
%M
Minute as a decimal number [00,59].  
%p
Locale's equivalent of either AM or PM.  
%S
Second as a decimal number [00,61].
%U
Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w
Weekday as a decimal number [0(Sunday),6].        
%W
Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x
Locale's appropriate date representation.    
%X
Locale's appropriate time representation.      
%y  
Year without century as a decimal number [00,99].    
%Y
Year with century as a decimal number.
%Z  
Time zone name (no characters if no time zone exists).  
%%  
A literal "%" character