How to extract a character from a string in python3

Keywords: python-3.x


I have a variable T in he form YYYY-MM-DD_HH:00:00, where YYYY is the 4-digit year, MM is the month and HH is the hour. I want to extract individual fields. Firstly when I do:

print("T = ",T)

I get

T =  [b'2' b'0' b'1' b'9' b'-' b'0' b'6' b'-' b'0' b'2' b'_' b'0' b'0' b':' b'0' b'0' b':' b'0' b'0']

In python2.7 I do:

myList = list(T[0:4])
yr = "".join(myList)

myList = list(T[5:7])
mn = "".join(myList)

myList = list(T[8:10])
dy = "".join(myList)

myList = list(T[11:13])
hr = "".join(myList)

These lines give me the digits.

However in python 3.7 I get stuck at the very first field

myList = list(T[0:4])
print("myList = ",myList) -> myList =  [b'2', b'0', b'1', b'9']
yr = "".join(myList)

gives error

TypeError: sequence item 0: expected str instance, numpy.bytes_ found


yr = b"".join(myList)


print("yr = ",yr) -> yr =  b'2019'

From here I am not able to extract the year digits.

print("yr = ",yr[0:3]) -> yr =  b'201'

print("yr = ",yr[1:4]) -> yr =  b'019'

I have also tried

newyr = yr.replace("b", "")

and p = yr.index("b") # find position of the letter "b" TypeError: argument should be integer or bytes-like object, not 'str'

All these do not work.

How do I get rid of the b and keep the year digits. Since python 2.7 will no longer be maintained from 2020, I need my code to work in python 3.x

Assistance will be appreciated.