TheDorf
TheDorf

Reputation: 1

datetime in python importing csv

Beginner Question - I am trying to import a CSV file into python, but seem to have a problem with date format

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

header = next(reader) 

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

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

print(data[0])

error message I get is

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

~/anaconda3/lib/python3.7/_strptime.py in _strptime_datetime(cls, data_string, format)
    575     """Return a class cls instance based on the input string and the
    576     format string."""
--> 577     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    578     tzname, gmtoff = tt[-2:]
    579     args = tt[:6] + (fraction,)

~/anaconda3/lib/python3.7/_strptime.py in _strptime(data_string, format)
    360     if len(data_string) != found.end():
    361         raise ValueError("unconverted data remains: %s" %
--> 362                           data_string[found.end():])
    363 
    364     iso_year = year = None

ValueError: unconverted data remains: ;1048.339966;1066.939941;1045.229980;1065.000000;1065.000000;1237600`enter code here`

ValueError: unconverted data remains

what does it mean and how to get about it? thx a lot.

Upvotes: 0

Views: 2141

Answers (1)

Marcus
Marcus

Reputation: 3524

It looks like your CSV is actually using semicolons as the delimiter instead of commas. This is causing the first "cell" to contain the data for all cells in the row, which the datetime parser is getting choked up on.

You can fix change your csv reader to use semicolons by changing line 3 from:

reader = csv.reader(file)

to

reader = csv.reader(file, delimiter=';')

Upvotes: 1

Related Questions