Search code examples
pythoncsvnumpydate-conversion

python - ValueError: time data does not match format


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.


Solution

  • 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.