12-Hour Time (H:MM AM/PM) Regex for Python
/^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$/iWhat this pattern does
This page provides a well-structured, multi-part regular expression for matching 12-hour time (h:mm am/pm), ported and verified for Python. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# 12-Hour Time (H:MM AM/PM)
# ReDoS-safe | RegexVault — Localization > Time Formats
import re
12hour_time_hmm_ampm_pattern = re.compile(r'^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$')
def validate_12hour_time_hmm_ampm(value: str) -> bool:
return bool(12hour_time_hmm_ampm_pattern.fullmatch(value))
# Example
print(validate_12hour_time_hmm_ampm("12:30 PM")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
12:30 PM | 13:00 PM |
1:05 AM | 0:30 AM |
11:59:59 PM | 12:60 PM |
12:00 AM | 12:30 |
9:30am | 12:30 pm extra |
12:00PM | — |
When to use this pattern
This pattern is drawn from the Localization > Time Formats category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
12:00 AM (midnight) and 12:00 PM (noon) confuse even native English speakers. Consider rejecting 12-hour format for any time-critical input and requiring 24-hour instead.
Technical Notes
12:00 AM = midnight, 12:00 PM = noon — the most commonly confused values. 12-hour format is standard in US, UK, Australia, and parts of Asia. Many others use 24-hour exclusively.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern