导入日期时间的“ NameError:名称'datetime'未定义”

时间:2018-07-09 13:31:16

标签: python-3.x

我知道有很多datetime未定义的帖子,但是它们似乎都忘记了datetime的明显导入。我不知道为什么会出现此错误。当我在iPython中执行每个步骤时,它都能很好地工作,但是该方法没有

import requests
import datetime

def daily_price_historical(symbol, comparison_symbol, limit=1, aggregate=1, exchange='', allData='true'):

    url = 'https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym={}&limit={}&aggregate={}&allData={}'\
        .format(symbol.upper(), comparison_symbol.upper(), limit, aggregate, allData)
    if exchange:
        url += '&e={}'.format(exchange)
    page = requests.get(url)
    data = page.json()['Data']
    df = pd.DataFrame(data)
    df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]

    datetime.datetime.fromtimestamp()

    return df

此代码会产生此错误:

Traceback (most recent call last):
  File "C:\Users\20115619\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-29-4f015e05113f>", line 1, in <module>
    rv.get_prices(30, 'ETH')
  File "C:\Users\20115619\Desktop\projects\testDash\Revas.py", line 161, in get_prices
    for symbol in symbols:
  File "C:\Users\20115619\Desktop\projects\testDash\Revas.py", line 50, in daily_price_historical
    df = pd.DataFrame(data)
  File "C:\Users\20115619\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py", line 4372, in __getattr__
    return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'time'

1 个答案:

答案 0 :(得分:1)

df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]

我认为这是问题所在。

该行末尾的数据框df没有属性.time

对于我值得的Python 3.6.0,这对我来说很完美:

import requests
import datetime
import pandas as pd

def daily_price_historical(symbol, comparison_symbol, limit=1, aggregate=1, exchange='', allData='true'):
    url = 'https://min-api.cryptocompare.com/data/histoday?fsym={}&tsym={}&limit={}&aggregate={}&allData={}'\
        .format(symbol.upper(), comparison_symbol.upper(), limit, aggregate, allData)
    if exchange:
        url += '&e={}'.format(exchange)
    page = requests.get(url)
    data = page.json()['Data']
    df = pd.DataFrame(data)
    df['timestamp'] = [datetime.datetime.fromtimestamp(d) for d in df.time]
    #I don't have the following function, but it's not needed to run this
    #datetime.datetime.fromtimestamp()
    return df

df = daily_price_historical('BTC', 'ETH')
print(df)

注意,我注释掉了调用我没有的外部函数的那一行。也许您有一个导致问题的全局变量?

根据评论

更新

我改用join来创建URL:

url = "".join(["https://min-api.cryptocompare.com/data/histoday?fsym=", str(symbol.upper()), "&tsym=", str(comparison_symbol.upper()), "&limit=", str(limit), "&aggregate=", str(aggregate), "&allData=", str(allData)])