0

I have string like this

INPUT:

date = '2017-02-03 14:07:03.840'

And how replace 2017-02-03 In order to on output I'll have

2017-02-03 14:07:03.840 => 2015-01-01 14:07:03.840

How to replace only date without time? Using re module

1
  • \d{4}-\d{1,2}-\d{1,2}? Commented Mar 4, 2017 at 13:22

1 Answer 1

4

You can use the following regex to select only the date and by substituting it with your desired date you can get the expected result :

\d{4}-\d{2}-\d{2}

python

import re
regex = r"\d{4}-\d{2}-\d{2}"
date = "2017-02-03 14:07:03.840"
subst = "2015-01-01"
result = re.sub(regex, subst, date, 0)
if result:
    print (result)
Sign up to request clarification or add additional context in comments.

2 Comments

How I can replace time in the new string? 14:07:03.840
@Maic use this regex \d+:\d+:[\d.]+

Your Answer

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