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


    关于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 notexplicitly 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.

     
  • 相关阅读:
    leetcode 763 划分字母区间
    leetcode 392 判断子序列
    Leetcode 665 修改一个数成为非递减数组 (Easy)
    leetcode 605 种花问题 贪心算法
    leetcode 452 用最少数量的箭引爆气球 贪心算法
    leetcode 455 分发饼干 贪心算法
    delphi中的 CLX Application
    delphi 之DCOM应用服务器定义函数
    SqlServer 之 sp_executesql系统存储过程的介绍和使用
    delphi 之调用WinSock的API获取本机的机器名称和IP地址
  • 原文地址:https://www.cnblogs.com/master-road/p/10619595.html
Copyright © 2020-2023  润新知