Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for timestamp

Tags:

python

regex

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.

like image 525
user1159454 Avatar asked Jul 26 '12 08:07

user1159454


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is the regex for date?

The regex matches on a date with the DD/MM/YYYY format and a "Date of birth:" or "Birthday:" prefix (Year min: 1900, Year max: 2020). For example: Date of birth: 12/01/1900.

What is a timestamp format?

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.


4 Answers

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.

like image 118
Martijn Pieters Avatar answered Sep 28 '22 16:09

Martijn Pieters


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'
like image 40
Jon Clements Avatar answered Sep 28 '22 17:09

Jon Clements


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

[0-9]{2}
like image 42
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 17:09

Ignacio Vazquez-Abrams


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

[0-9]{2}:[0-9]{2}:[0-9]{2}
like image 23
Mark Byers Avatar answered Sep 28 '22 17:09

Mark Byers