Split a string into Name and Time

Viewed 43

I want to split a string as it contains a combined string of name and time. I want to split as shown in example below:

Complete string

cDOT_storage01_esx_infra02_07-19-2021_04.45.00.0478

Desired output

cDOT_storage01_esx_infra02 07-19-2021

Efforts performed, not giving desired output

j['name'].split("-")[0], j['name'].split("-")[1][0:10]

3 Answers

Use rsplit. The only two _ you care about are the last two, so you can limit the number of splits rsplit will attempt using _ as the delimiter.

>>> "cDOT_storage01_esx_infra02_07-19-2021_04.45.00.0478".rsplit("_", 2)
['cDOT_storage01_esx_infra02', '07-19-2021', '04.45.00.0478']

You can index the resulting list as necessary to get your final result.

If all the strings follow the same pattern (separated by an underscore(_)), you can try this.

(Untested)

string = "cDOT_storage01_esx_infra02_07-19-2021_04.45.00.0478"
splitted = list(map(str, string.split('_')))
# splitted[-1] will be "04.45.00.0478"
# splitted[-2] will be "07-19-2021"
# Rest of the list will contain the front part

other = splitted.pop()
date = splitted.pop()
name = '_'.join(splitted)

print(name, date)

You use regex for searching and printing.

import re
txt = "cDOT_storage01_esx_infra02_07-19-2021_04.45.00.0478"
# searching the date in the string
x = re.search("\d{2}-\d{2}-\d{4}", txt)
if x:
    print("Matched")
    a = re.split("[0-9]{2}-[0-9]{2}-[0-9]{4}", txt)
    y = re.compile("\d{2}-\d{2}-\d{4}")
    print(a[0][:-1] , " ", y.findall(txt)[0])
else:
    print("No match")

Output:

Matched
cDOT_storage01_esx_infra02   07-19-2021
Related