How to validate time in 12 | Python3 program to validate the time in 12 - hour format using Regular Expression . ; Function to validate the time in 12 - hour format . ; Regex to check valid time in 12 - hour format . ; Compile the ReGex ; If the time is empty return false ; Return if the time matched the ReGex ; Driver Code . ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 :
import re NEW_LINE def isValidTime ( time ) : NEW_LINE INDENT regexPattern = " ( 1[012 ] ▁ [ 1-9 ] ) : " + " [ 0-5 ] [ 0-9 ] ( \\s ) " + " ? ( ? i ) ( am ▁ pm ) " ; NEW_LINE compiledPattern = re . compile ( regexPattern ) ; NEW_LINE if ( time == None ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if re . search ( compiledPattern , time ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = "12:15 ▁ AM " ; NEW_LINE print ( isValidTime ( str1 ) ) ; NEW_LINE str2 = "9:45PM " ; NEW_LINE print ( isValidTime ( str2 ) ) ; NEW_LINE str3 = "1:15" ; NEW_LINE print ( isValidTime ( str3 ) ) ; NEW_LINE str4 = "17:30" ; NEW_LINE print ( isValidTime ( str4 ) ) ; NEW_LINE DEDENT