Time regex (24-hour and 12-hour)

Regex for 24-hour HH:MM(:SS) times and 12-hour times with AM/PM. Tested examples.

Pattern
/^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/

Matches

  • 00:00
  • 23:59
  • 09:30:15

Doesn't match

  • 24:00
  • 9:5
  • 12:60

Alternative: 12-hour with AM/PM

^(0?[1-9]|1[0-2]):[0-5]\d\s?(?:[AaPp][Mm])$

Notes

  • Hours are split into 00–19 and 20–23 so 24 and above fail.
  • Allow a single-digit hour with ([01]?\d|2[0-3]).

Code

JavaScript

const re = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?', value))

Try it on your own input

The live tester adds the g and m flags so every line is checked separately.

Questions

How do I also accept 24:00?

Add it as an alternative: ^(?:([01]\d|2[0-3]):([0-5]\d)|24:00)$.

More patterns

Email regexPhone number regexURL regexIP address regexDate regexUUID regexHex color regexPassword regex