[Python] ValueError: Traceback (most recent call last) <ipython-input-15-d27c936e2293> in...

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to read the data from a csv file and I am getting this error:


    ValueError Traceback (most recent call last)
    <ipython-input-15-d27c936e2293> in <module>()
    11 for row in header:
    12 # row = [Date, Open, High, Low, Close, Volume, Adj. close]
    ---> 13 date = datetime.strptime(row[0], '%m/%d/%Y')
    14 open_price = float(row[1])
    15 high = float(row[2])

    ~/anaconda3/lib/python3.6/_strptime.py in _strptime_datetime(cls, data_string, format)
    563 """Return a class cls instance based on the input string and the
    564 format string."""
    --> 565 tt, fraction = _strptime(data_string, format)
    566 tzname, gmtoff = tt[-2:]
    567 args = tt[:6] + (fraction,)

    ~/anaconda3/lib/python3.6/_strptime.py in _strptime(data_string, format)
    360 if not found:
    361 raise ValueError("time data %r does not match format %r" %
    --> 362 (data_string, format))
    363 if len(data_string) != found.end():
    364 raise ValueError("unconverted data remains: %s" %

    ValueError: time data 'D' does not match format '%m/%d/%Y'


    Here's my code:

    import csv
    from datetime import datetime

    path ="google_stock_data.csv"
    file = open (path, newline = '')
    reader = csv.reader(file)

    header = next (reader)

    data = []
    for row in header:
    # row = [Date, Open, High, Low, Close, Volume, Adj. close]
    date = datetime.strptime(row[0], '%m/%d/%Y')
    open_price = float(row[1])
    high = float(row[2])
    low = float(row[3])
    close = float(row[4])
    volume = float(row[5])
    adj_close = float(row[6])

    data.append([date, open_price, high, low, close, volume, adj_close])

    print(data[0])


    NOTE: The data in the file looks like this:

    Date Open High Low Close Volume Adj Close

    8/19/14 585.002622 587.342658 584.002627 586.862643 978600 586.862643
    8/18/14 576.11258 584.512631 576.002598 582.162619 1284100 582.162619
    8/15/14 577.862619 579.382595 570.522603 573.482626 1519100 573.482626
    8/14/14 576.182596 577.902645 570.882599 574.652582 985400 574.652582


    Why is that? Isn't the data being converted to the proper type? Please help. How can I fix it?

    Thanks.

    Continue reading...

Compartilhe esta Página