user3682563 user3682563 - 2 years ago 204
Python Question

python: loop through a string and find dates (YYYY-MM-DD) and replace them with date (found date + 5 days)

Input

x = "These are the dates 2017-09-23 and 2017-01-03"


Output

These are the dates 2017-09-28 and 2017-01-08





I was thinking of using re.sub. But apparently re.sub only allows replacement that is independent of the string being searched. So, I can't think of any way to do it.

Answer Source

You're working with dates, so simple arithmetic is not going to be enough. You'll need to extract and convert those strings to datetime, and then add days using timedelta. You can use re.sub with a callback to facilitate this easily.

import re
import datetime
from datetime import datetime as dt

def foo(m):
    date_string = dt.strptime(m.group(0), '%Y-%m-%d')
    return (date_string + datetime.timedelta(days=5).strftime('%Y-%m-%d')

x = "These are the dates 2017-09-23 and 2017-01-03"
y = re.sub('\d{4}(?:-\d{2}){2}', foo, x)
print(y)

Output

These are the dates 2017-09-28 and 2017-01-08

Regex

\d{4}          # 4 digits
(?:            # non-capturing group 
 -             # hyphen
\d{2}          # 2 digits
){2}           # group must appear twice
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download