When working with date and time data in Python, you may need to be able to match a 12-hour or 24-hour time format. This task can easily be accomplished using regular expressions.
12hour time format
without seconds
(?:0?[0-9]|1[0-2])[-:][0-5][0-9]\s*[apAP][mM]
copy
The above regular expression matches a time in the format of "hh:mm am/pm" or "hh:mmam/pm". Here's a breakdown of the different components:
(?:0?[0-9]|1[0-2])
matches the hour part of the time. It can be either a single digit hour (optional leading zero) ranging from 0 to 9, or a two-digit hour ranging from 10 to 12.[-:]
matches a hyphen or a colon, which separates the hour and minute parts of the time.[0-5][0-9]
matches the minute part of the time. It matches a digit from 0 to 5 followed by any digit from 0 to 9, representing a minute from 00 to 59.\s*
matches zero or more whitespace characters (spaces or tabs), allowing for optional spacing between the minute part and the AM/PM indicator.[apPM][mM]
matches the AM/PM indicator. It can be either "am" or "pm", case-insensitive.
With seconds
(?:0?[0-9]|1[0-2])[-:][0-5][0-9][-:][0-5][0-9]\s*[apP][mM]
copy
In the above example we added ^ and $ at the start and end of the pattern respectively in order to match the full string.
24hr time Format
without seconds
(?:[01][0-9]|2[0-3])[-:hH][0-5][0-9]
copy
The regular expression above pattern matches a time in the format "hh:mm" in a 24-hour clock format. Let's break down the different components:
(?:[01][0-9]|2[0-3])
matches the hour part of the time. It can be either a single-digit hour (00-09) or a two-digit hour (10-23).[-:hH]
matches a hyphen, colon, "h" or "H", which separates the hour and minute parts of the time.[0-5][0-9]
matches the minute part of the time. It represents a digit from 0 to 5 followed by any digit from 0 to 9, allowing for values from 00 to 59.
with the seconds
(?:[01][0-9]|2[0-3])[-:hH][0-5][0-9][-:mM][0-5][0-9]
copy