fail to use numpy loadtxt to convert date with python3.6

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

My code as follows:

import numpy as np import matplotlib.dates as mdates  stockFile = 'HistoricalQuotes.csv'  dates, close = np.loadtxt(stockFile, delimiter=',', unpack=True, usecols=(0,1), \                           converters = {0: mdates.strpdate2num('%Y-%m-%d')}) print("Dates = ", dates) 

and the Traceback:

Traceback (most recent call last):   File "/Users/zdlzdlxs/Documents/workspace/pynum_practice/part3/simplestats.py", line 7, in <module>     converters = {0: mdates.strpdate2num('%Y-%m-%d')})   File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/numpy/lib/npyio.py", line 1024, in loadtxt     items = [conv(val) for (conv, val) in zip(converters, vals)]   File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/numpy/lib/npyio.py", line 1024, in <listcomp>     items = [conv(val) for (conv, val) in zip(converters, vals)]   File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/matplotlib/dates.py", line 287, in __call__     return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6]))   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 559, in _strptime_time     tt = _strptime(data_string, format)[0]   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 329, in _strptime     raise TypeError(msg.format(index, type(arg))) TypeError: strptime() argument 0 must be str, not <class 'bytes'> 

I've tried to find solutions in stackoverflow but failed. Could anyone help me to convert datetime correctly? Thanks a lot.

回答1:

This date converter expects a regular string, which in Py3 is unicode. But loadtxt loads the text as bytestrings:

In [12]: mdates.strpdate2num('%Y-%m-%d')(b'1999-01-31') --------------------------------------------------------------------------- .... TypeError: strptime() argument 0 must be str, not <class 'bytes'> 

Modifying the converter to decode the bytestring should take care of the issue:

In [13]: fn = lambda astr: mdates.strpdate2num('%Y-%m-%d')(astr.decode())  In [14]: fn(b'1999-01-01') Out[14]: 729755.0 

testing in loadtxt:

In [15]: txt=b"""1999-01-01     ...: 2000-03-03     ...: 2015-12-12     ...: """  In [16]: np.loadtxt(txt.splitlines(), converters={0:fn}) Out[16]: array([ 729755.,  730182.,  735944.]) 


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