Untitled
indreshp135
python
a month ago
2.9 kB
3
Indexable
import re # Define custom exceptions for invalid date format and invalid month name class InvalidDateFormat(Exception): pass class InvalidMonthName(Exception): pass # Regex patterns to validate specific components (Date and Time) pattern_date1 = r'^\d{4}-(0[1-9]|1[0-2])-\d{2}$' # Date part for YYYY-MM-DD pattern_date2 = r'^\d{4}\/(0[1-9]|1[0-2])\/\d{2}$' # Date part for YYYY/MM/DD pattern_date3 = r'^(0[1-9]|[12][0-9]|3[01])\s([Jj]anuary|[Ff]ebruary|[Mm]arch|[Aa]pril|[Mm]ay|[Jj]une|[Jj]uly|[Aa]ugust|[Ss]eptember|[Oo]ctober|[Nn]ovember|[Dd]ecember)\s\d{4}$' # Date part for DD Month YYYY pattern_time = r'(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$' # Time part for HH:mm:ss # Function to validate the date-time format def validate_date_time(text): # Separate date and time based on space between them if ' ' not in text: raise InvalidDateFormat("Invalid date and time format") date_part, time_part = text.split(' ', 1) # Check if the date part is valid is_valid_date = ( re.match(pattern_date1, date_part) or re.match(pattern_date2, date_part) or re.match(pattern_date3, date_part) ) # Check if the time part is valid is_valid_time = re.match(pattern_time, time_part) # Handle month validation for pattern3 (DD Month YYYY) if re.match(pattern_date3, date_part): # Extract the month name (case-insensitive) month_name = date_part.split(' ')[1].lower() valid_months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] # Check if the month is valid if month_name not in valid_months: raise InvalidMonthName("Invalid month name") # If neither date nor time is valid if not is_valid_date and not is_valid_time: raise InvalidDateFormat("Invalid date and time format") # If date is invalid elif not is_valid_date: raise InvalidDateFormat("Invalid date or time format") # If time is invalid elif not is_valid_time: raise InvalidDateFormat("Invalid date or time format") else: print(f"'{text}' is a valid date-time format.") # Example usage: text1 = "2025-03-22 14:30:00" text2 = "2025/03/22 14:30:00" text3 = "22 March 2025 14:30:00" text4 = "2025-13-22 14:30:00" # Invalid date (month 13) text5 = "2025-03-22 24:60:00" # Invalid time text6 = "22 Munday 2025 14:30:00" # Invalid month name # Validate the date-time formats try: validate_date_time(text1) # Valid input validate_date_time(text2) # Valid input validate_date_time(text3) # Valid input validate_date_time(text4) # Invalid date validate_date_time(text5) # Invalid time validate_date_time(text6) # Invalid month name except InvalidDateFormat as e: print(e) except InvalidMonthName as e: print(e)
Editor is loading...
Leave a Comment