简体   繁体   中英

Converting a loadtxt column to a weekday: TypeError: strptime() argument 1 must be str, not bytes

I'm trying to load data from a CSV file, and convert one column with a date, to a week number. I am getting below mentioned TypeError :

import numpy as np

from datetime import datetime

def datestr2num(s):
    return datetime.strptime(s, "%d-%m-%Y").date().weekday()

dates, close = np.loadtxt(
    'data.csv', delimiter=',', usecols=(1,6), 
    converters={1: datestr2num}, unpack=True)

print("Dates =", dates)

Error:

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

I tried to execute this program on Python 3.5.2 -Anaconda custom (64-bit)

Converters are given the raw bytes value read from the file; you need to decode these to a string first if you want to parse them as a datetime value. ASCII should suffice as your input is simply a series of digits and dashes to form a date:

def datestr2num(s):
    s = s.decode('ascii')
    return datetime.strptime(s, "%d-%m-%Y").weekday()

Note: I removed the .date() call; the datetime object supports the datetime.weekday() method directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM