【问题标题】:TypeError: unsupported operand type(s) for +: 'float' and 'datetime.timedelta'类型错误:+ 不支持的操作数类型:'float' 和 'datetime.timedelta'
【发布时间】:2015-08-20 14:07:27
【问题描述】:

我收到此错误。从这一行:

ohlc[0][i+1] = ohlc[0][i] + dt.timedelta(days=1)

这里是上下文:

stock_price_url = 'https://www.quandl.com/api/v3/datasets/WIKI/AAPL/data.csv?start_date=2015-06-01&order=asc&end_date=2015-08-01&collapse=daily'
source_code = urllib.urlopen(stock_price_url).read().decode()
stock_data = []
split_source = source_code.split('\n')
for line in split_source:
    split_line = line.split(',')
    if 'Date' not in line:
        stock_data.append(line)


date, openp, highp, lowp, closep, volume = np.loadtxt(stock_data,
                                                      delimiter=',',
                                                      unpack=True,
                                                      converters={0:strpdate2num('%Y-%m-%d')},
                                                      usecols=(0,1,2,3,4,5))

x = 0
y = len(date)
ohlc

while x < y:
    append_me = date[x], openp[x], closep[x], highp[x], lowp[x], volume[x]
    ohlc.append(append_me)
    x+=1

# the dates in my example file-set are very sparse (and annoying) change the dates to be sequential

for i in range(len(date)-1):
    ohlc[0][i+1] = ohlc[0][i] + dt.timedelta(days=1)

试图从这个answer做类似的事情:

# the dates in my example file-set are very sparse (and annoying) change the dates to be sequential
for i in range(len(r)-1):
    r['date'][i+1] = r['date'][i] + datetime.timedelta(days=1)

任何帮助都会非常棒。

【问题讨论】:

  • 所以ohlc[0][i]float...你期待什么?
  • 更新问题,请看一下。
  • 但这要求您从date/datetime 开始 - 也许您真正的问题是“我如何将这些数据中的一些设为date?” i>,相关文档可能已回答。
  • 即这仅在 r['date'][i]datetime 对象时才有效
  • 谢谢大家,我现在明白了。

标签: python matplotlib


【解决方案1】:

该错误是由于尝试将两种不同的数据类型(浮点数和日期)相加而产生的。

从粗略的谷歌上,matplotlib.dates num2date 函数在这种情况下可能会有所帮助。 datetime documentation 也可能有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多