Select specific substing – dynamic indexing

Using str.split with list slicing

Ex:

import datetime

for i in ("X-XXX_2020-11-05_13-54-55-555__XX.csv", "X-XXX_2020-11-05_13-54-55-555__XXX.csv"):
    print(datetime.datetime.strptime("_".join(i.split("_")[1:3]), "%Y-%m-%d_%H-%M-%S-%f"))

OR using regex.

Ex:

import re
import datetime

for i in ("X-XXX_2020-11-05_13-54-55-555__XX.csv", "X-XXX_2020-11-05_13-54-55-555__XXX.csv"):
    d = re.search(r"(?<=_)(.+)(?=__)", i)
    if d:
        print(datetime.datetime.strptime(d.group(1), "%Y-%m-%d_%H-%M-%S-%f"))

Output:

2020-11-05 13:54:55.555000
2020-11-05 13:54:55.555000

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top