python - ValueError: time data does not match format

与世无争的帅哥 提交于 2019-12-10 12:05:53

问题


I downloaded my CSV file TSLA.csv from here. It has a header line and 7 columns, first of which is date, the others are floats and ints.

I want to be able to get a numpy array out of it:

import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import urllib


def bytespdate2num(fmt, encoding="utf-8"):
    strconverter = mdates.strpdate2num(fmt)
    def bytesconverter(b): 
        s = b.decode(encoding)
        return strconverter(s)
    return bytesconverter

with open("TSLA.CSV", "r") as csvfile:
    stock_price = csv.reader(csvfile, delimiter=" ")
    stock_price = list(stock_price)


date, closep, highp, lowp, openp, volume = np.loadtxt(stock_price, 
                                                      delimiter = ",",
                                                      unpack = True,
                                                      skiprows=1,
                                                      converters={0: bytespdate2num("%Y-%m-%d")})

Trouble is, I get the following error:

ValueError: time data "['2010-06-29" does not match format '%Y-%m-%d'

I have double-checked the format and checked other questions around here, but those were mostly about the wrong format... I can't see the problem here. Help appreciated.


回答1:


Okay, I believe the problem is here:

Have a look again at the error, it says "['2010-06-29" does not match data format. That is because you are not trying to parse the date alone, look at the double quotes that surround the date.

You are trying to parse:

['2010-06-29

There's an extra [' in your string that is messing things up.



来源:https://stackoverflow.com/questions/46090981/python-valueerror-time-data-does-not-match-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!