About TypeError: strptime () argument 1 must be str, not bytes parsing, typeerrorstrptime
An error occurs when datetime. strptime (s, fmt) is used to output the result date.
TypeError: strptime () argument 1 must be str, not bytes
My source code is as follows:
Def datestr2num (s ):
Return datetime. strptime (s, "% d-% m-% Y"). date (). weekday ()
Dates=np.loadtxt('data.csv ', delimiter =', ', usecols = (1,), converters = {1: datestr2num}, unpack = True)
The contents of data.csv are as follows:
When the Editor opens the data.csv file, it extracts the array values of the 2nd columns in the table and returns them to dates. The second column value is a date format string, but because we open the second column value in binary encoding format, the returned value is a bytes string. Therefore, you need to decode the string using the decode ('asii') function to convert it to the string format.
Def datestr2num (s ):
Return datetime. strptime (S. decode ('ascii '), "% D-% m-% Y"). date (). weekday ()
Dates=np.loadtxt('data.csv ', delimiter =', ', usecols = (1,), converters = {1: datestr2num}, unpack = True)
The English Excerpt from the Internet is as follows:
line
Is a bytestring, because you opened the file in binary mode. You'll need to decode the string; if it is a date string matching the pattern, you can simply use ASCII:
time.strptime(line.decode('ascii'), '%Y-%m-%d ...')
You can add'ignore'
Argument to ignore anything non-ASCII, but chances are the line won't fit your date format then anyway.
Note that you cannot pass a value that containsMoreThan the parsed format in it; a line with other text on it not explicitly covered bystrptime()
Pattern will not work, whatever codec you used.
And if your input really varies that widely in codecs, you'll need to catch exceptions one way or another anyway.
Aside from UTF-16 or UTF-32, I wocould not expect CT you to encounter any codecs that use different bytes for the arabic numerals. if your input really mixes multi-byte and single-byte codecs in one file, you have a bigger problem on your hand, not in the least because newline handling will be majorly messed up.