How to validate time in 24 | Python3 program to validate the time in 24 - hour format using Regular Expression . ; Function to validate the time in 24 - hour format ; Regex to check valid time in 24 - hour format . ; Compile the ReGex ; If the time is empty return false ; Pattern class contains matcher ( ) method to find matching between given time and regular expression . ; Return True if the time matched the ReGex otherwise False ; Driver Code . ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import re NEW_LINE def isValidTime ( time ) : NEW_LINE INDENT regex = " ^ ( [01 ] ? [0-9 ] ▁ 2[0-3 ] ) : [ 0-5 ] [ 0-9 ] $ " ; NEW_LINE p = re . compile ( regex ) ; NEW_LINE if ( time == " " ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT m = re . search ( p , time ) ; NEW_LINE if m is None : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = "13:05" ; NEW_LINE print ( str1 , " : ▁ " , isValidTime ( str1 ) ) ; NEW_LINE str2 = "02:15" ; NEW_LINE print ( str2 , " : ▁ " , isValidTime ( str2 ) ) ; NEW_LINE str3 = "24:00" ; NEW_LINE print ( str3 , " : ▁ " , isValidTime ( str3 ) ) ; NEW_LINE str4 = "10:60" ; NEW_LINE print ( str4 , " : ▁ " , isValidTime ( str4 ) ) ; NEW_LINE str5 = "10:15 ▁ PM " ; NEW_LINE print ( str5 , " : ▁ " , isValidTime ( str5 ) ) ; NEW_LINE DEDENT