2

I am dealing with strings that need to be converted into dates in Python. In a normal situation, my string would have %d/%m/%Y %H:%M:%S. For instance: 18/02/2013 09:21:14

However in some occasion I could obtain something like %d/%m/%Y %H:%M:%S:%ms, such as:06/01/2014 09:52:14:78

I would like to get rid of that ms bit but I need to figure out how. I have been able to create a regular expression which can test if the date matches:

    mydate = re.compile("^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2})) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$")
    s = "06/01/2014 09:52:14:78"
    bool(mydate.match(s))

>>> False

However I do not know how to obtain only the interesting part, i.e 06/01/2014 09:52:14 Any ideas?

1
  • 2
    Why not just try to strptime the string? If it fails, rsplit to remove the last part and try again. Commented Nov 28, 2014 at 14:37

2 Answers 2

2

You can use a positive lookbehind and re.sub():

>>> re.sub(r'(?<=\d{2}:\d{2}:\d{2}).*','','06/01/2014 09:52:14:78')
'06/01/2014 09:52:14'

Regular expression visualization

Debuggex Demo

Sign up to request clarification or add additional context in comments.

Comments

1

How about the re.sub function

>>> re.sub(r'( \d{2}(:\d{2}){2}).*$',r'\1','06/01/2014 09:52:14:78')
'06/01/2014 09:52:14'
>>> re.sub(r'( \d{2}(:\d{2}){2}).*$,r'\1','8/02/2013 09:21:14')
'8/02/2013 09:21:14'
  • ( \d{2}(:\d{2}){2}) matcheshours:min:sec` saved in capture group 1

  • .*$ matches the milliseconds

  • r'\1' replaced with contents of the first caputre group

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.