-6

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
pom
  • 230
  • 5
  • 17

2 Answers2

2

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
cs95
  • 379,657
  • 97
  • 704
  • 746
-1
import re
from datetime import datetime, timedelta

dateString = "hello hello 2017-08-13, 2017-09-22"

dates = re.findall('(\d+[-/]\d+[-/]\d+)', dateString)

for d in dates:
    originalDate = d

    newDate = datetime.strptime(d, "%Y-%m-%d") 
    newDate = newDate + timeDelta(days=5)
    newDate = datetime.strftime(newDate, "%Y-%m-%d")   

    dateString = dateString.replace(originalDate, newDate)

Input: hello hello 2017-08-13, 2017-09-22

Output: hello hello 2017-08-18, 2017-09-27

Godron629
  • 302
  • 1
  • 7
  • This doesn't answer the question, as you are supposed to be able to substitute the original date with the new one. – cs95 Oct 01 '17 at 23:56
  • Ok, I mean it's pretty easy to substitute a string but I will edit my answer. – Godron629 Oct 01 '17 at 23:58
  • Substitute with the assumption that there are N dates, and you don't know where a string could occur. – cs95 Oct 01 '17 at 23:59
  • @Godron629 This still DOES NOT answer the question. Are you really expecting a str replace call to have the same level of flexibility? – cs95 Oct 03 '17 at 01:30
  • @user3682563 Note that this is not going to work if you even add a single extra date into the string. Did you even read the solution? – cs95 Oct 03 '17 at 01:30
  • @user3682563 Even if this answer did solve the problem (which it doesn't by the way), it performs a number of unnecessary steps and operations, is highly inefficient, and daresay misleading to readers. – cs95 Oct 03 '17 at 01:31