smcodemeister
smcodemeister

Reputation: 17

How to extract date from a string?

I have this weird string:

'": "1899-12-30 14:50:00.000"": " "'

I need to just extract the date. I have looked at all the different python string manipulation functions but I just can't seem to find one that works for this interesting format.

Thanks

Upvotes: 0

Views: 108

Answers (2)

Andrew Ryan
Andrew Ryan

Reputation: 1601

Based on your string if you just want 1899-12-30 you could do:

'": "1899-12-30 14:50:00.000"": " "'.split(' ')[1][1:]

if you want the full 1899-12-30 14:50:00.000 you could do

'": "1899-12-30 14:50:00.000"": " "'.split('"')[2]

Explanation:

taking the string we are splitting the string by its characters in the first example a space and in the second a double quote as those characters surround the date element. The split function creates a list in which we access the element that we would like in the first case the second element (0 index list) while the second list we grab the third element. For the first Example printing out the output before we do a slice of the sting would give an extra double quote before the date, therefore we take the first element off of the string to only get the date.

Upvotes: 1

Thomasi Muc
Thomasi Muc

Reputation: 164

What about this solution:

mys = '": "1899-12-30 14:50:00.000"": " "'
print(mys.strip('": "'))

Upvotes: 1

Related Questions