user1159454
user1159454

Reputation: 3317

Regex for timestamp

I'm terrible at regex apparently, it makes no sense to me...

I'd like an expression for matching a time, like 01:23:45 within a string.

I tried this

(r'(([0-9]*2)[:])*2([0-9]*2)

but it's not working. I need to be able to get the entire timestamp. Others I've tried have only found like 2 digits in it.

Upvotes: 7

Views: 28644

Answers (5)

Gaurav Jain
Gaurav Jain

Reputation: 1865

import re

timestamp_regex = r'(2[0-3]|[01][0-9]|[0-9]):([0-5][0-9]|[0-9]):([0-5][0-9]|[0-9])'


print(bool(re.match(timestamp_regex, '01:23:45')))  # True
print(bool(re.match(timestamp_regex, '01:01:45')))  # True
print(bool(re.match(timestamp_regex, '01:01:01')))  # True
print(bool(re.match(timestamp_regex, '1:1:1')))     # True
print(bool(re.match(timestamp_regex, '25:1:1')))    # False

demo: https://ideone.com/eE0Pnb

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142216

Why even use a regex - use the proper datetime functions and get validation thrown in for free...

from datetime import datetime
time = datetime.strptime('01:23:45', '%H:%M:%S').time()
print time.hour, time.minute, time.second
# 1 23 45

Duff time:

>>> datetime.strptime('99:45:63', '%H:%M:%S')
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    datetime.strptime('99:45:63', '%H:%M:%S')
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '99:45:63' does not match format '%H:%M:%S'

Upvotes: 5

Mark Byers
Mark Byers

Reputation: 839044

Instead of *2 you should be using {2}.

[0-9]{2}:[0-9]{2}:[0-9]{2}

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1124518

You have your repeaters wrong I'm afraid:

r'\d{2}:\d{2}:\d{2}'

The correct syntax is {n,m} for minimum and maximum digits, or {n} for an exact match. The \d character class is also easier to use that [0-9]; it means the same thing for regular (non-Unicode) matching.

Upvotes: 12

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799290

The proper specifier for repeating the previous match twice is {2}.

[0-9]{2}

Upvotes: 2

Related Questions