简体   繁体   English

python中导入日期时间csv

[英]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 初学者问题-我正在尝试将CS​​V文件导入python,但是日期格式似乎有问题

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 ValueError:保留未转换的数据

what does it mean and how to get about it? 这是什么意思,如何实现? thx a lot. 多谢。

It looks like your CSV is actually using semicolons as the delimiter instead of commas. 看起来您的CSV实际上是使用分号而不是逗号作为分隔符。 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: 您可以通过更改第3行的内容来解决将csv阅读器更改为使用分号的问题:

reader = csv.reader(file)

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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