关于TypeError: strptime() argument 1 must be str, not bytes解析

在使用datetime.strptime(s,fmt)来输出结果日期结果时,出现错误

TypeError: strptime() argument 1 must be str, not bytes

我的源代码如下

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)

data.csv内容如下

编译器在打开data.csv文件时,将表格里的第2列数组值提取出来返回给dates,第二列值是日期格式字符串,但因为我们是以二进制编码的格式打开第二列值是,返回的值字节字符串bytes,所以需要把它便会string,则对字符串解码用函数decode('asii'),变成string格式。

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)

 

从网上摘抄的英文解释如下:

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 a '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 contains more than the parsed format in it; a line with other text on it not explicitly covered by the strptime() 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 would not expect 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.

转载于:https://www.cnblogs.com/zz22--/p/7496345.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值