Python Forum
Grabbing a Subset of a String - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Grabbing a Subset of a String (/thread-19217.html)



Grabbing a Subset of a String - acemurdoc - Jun-18-2019

I need to create a new field we can call Date_Time_txt, which is based off of a long string (!FolderPath!). Example of the full string: "Call Loc/Folder/(555) 555-5555 - 2/27/2019 8:52:34 AM/RoomB". I initially started the code as Date_Time_txt= !FolderPath![42:64], which would start at the date and grab the time, but because of varying time and date characters, I also grab "/R" on some sets. How can I run the function to just grab the date and time?


RE: Grabbing a Subset of a String - ichabod801 - Jun-18-2019

I would go with a regular expression (the re module). Regular expressions are used in tons of languages, so if you did a web search for "date regular expression" I'm sure you would find one fitting your requirements.


RE: Grabbing a Subset of a String - acemurdoc - Jun-18-2019

(Jun-18-2019, 02:26 PM)ichabod801 Wrote: I would go with a regular expression (the re module). Regular expressions are used in tons of languages, so if you did a web search for "date regular expression" I'm sure you would find one fitting your requirements.
Thanks!


RE: Grabbing a Subset of a String - perfringo - Jun-18-2019

If structure of strings is similar then one can achieve desired result also without re

>>> s = "Call Loc/Folder/(555) 555-5555 - 2/27/2019 8:52:34 AM/RoomB"
>>> " ".join(s.rsplit("/", maxsplit=1)[0].rsplit(maxsplit=3)[-3:])
'2/27/2019 8:52:34 AM'