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.
$ 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.
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.
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.
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.
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'
The proper specifier for repeating the previous match twice is {2}
.
[0-9]{2}
Instead of *2
you should be using {2}
.
[0-9]{2}:[0-9]{2}:[0-9]{2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With