1

I have a string as follows: 2020-01-01T16:30.00 - 1.00. I want to select the string that is between T and - , i.e. I want to be able to select 16:30.00 out of the whole string and convert it to a float. Any help is appreciated.

5
  • You should use datetime type for date/time data. Commented Jul 6, 2020 at 14:49
  • The data comes in the format I showed. How to I select the time part out of it. Commented Jul 6, 2020 at 14:50
  • df['your_column'].apply( lambda x: str(x)[-15:-7] ), if and only if the format stays the same Commented Jul 6, 2020 at 14:59
  • It doesn't stay the same, I am looking for something general. Commented Jul 6, 2020 at 15:00
  • I found the following answer that does it efficiently. stackoverflow.com/questions/39662149/… Commented Jul 6, 2020 at 15:06

1 Answer 1

1

If you have a pandas Series s like this

import pandas as pd
s = pd.Series(["2020-01-01T16:30.00 - 1.00", "2020-12-04T00:25.00 - 14.00"])

you can use

s.str.replace(".+T", "").str.replace(" -.+", "")
# 0    16:30.00
# 1    00:25.00
# dtype: object

Basically, you first substitute with an empty string everything that precedes the T and the T itself. Then, you substitute with an empty string the part starting with - (there is a whitespace before the small dash).


Another option is to use groups of regular expressions to match particular patterns and select only one of the groups (in this case the second, .+)

import re
s.apply(lambda x: re.match("(.+T)(.+)( -.+)", x).group(2))
# 0    16:30.00
# 1    00:25.00
# dtype: object
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, using datetime library is another way to do it. I found it in one of the stackoverflow answers.
Seen, very useful link!
@S_Scouse Just added another solution if you want to check it out
Thank you, very useful. I might use it for some other string selection need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.