无法使用numpy loadtxt与python3.6转换日期

时间:2017-10-18 16:15:26

标签: python numpy datetime

我的代码如下:

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)

和追溯:

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'>

我试图在stackoverflow中找到解决方案,但失败了。 任何人都可以帮我正确转换日期时间吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

这个日期转换器需要一个常规字符串,在Py3中是unicode。但是loadtxt将文本加载为bytestrings:

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

将转换器修改为decode bytestring应该解决问题:

In [13]: fn = lambda astr: mdates.strpdate2num('%Y-%m-%d')(astr.decode())

In [14]: fn(b'1999-01-01')
Out[14]: 729755.0

在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.])