user5639219
user5639219

Reputation:

Python regular expression replace date

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

Upvotes: 0

Views: 3689

Answers (1)

m87
m87

Reputation: 4523

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)

Upvotes: 4

Related Questions