Python AttributeError: 'datetime.datetime' 对象没有属性 'timestamp'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50650704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:34:41  来源:igfitidea点击:

AttributeError: 'datetime.datetime' object has no attribute 'timestamp'

python

提问by bullybear17

Please Help - I keep receiving the following Traceback Error:

请帮助 - 我不断收到以下回溯错误:

Currently Running Python 2.0

当前运行 Python 2.0

I'm attempting to utilize Python's Plotly library to display an infographic illustrating bitcoin prices. I've tried importing datetime at the top of my code but this doesn't appear to solve the problem.

我正在尝试利用 Python 的 Plotly 库来显示说明比特币价格的信息图。我试过在我的代码顶部导入日期时间,但这似乎不能解决问题。

Traceback (most recent call last):
  File "project_one.py", line 165, in <module>
    crypto_price_df = get_crypto_data(coinpair)
  File "project_one.py", line 155, in get_crypto_data
    json_url = base_polo_url.format(poloniex_pair, start_date.timestamp(), end_date.timestamp(), pediod)
AttributeError: 'datetime.datetime' object has no attribute 'timestamp'

My Code Starts Here

我的代码从这里开始

import numpy as np
import pandas as pd
from pandas import Series, DataFrame, Panel
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import seaborn as sns
import sklearn as sk
import scipy as sp
import os
import pickle
import quandl
import datetime
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.figure_factory as ff
from plotly import tools
from plotly.offline import iplot, init_notebook_mode
from IPython.display import display, HTML
init_notebook_mode(connected=True)


def get_quandl_data(quandl_id):

    cache_path = '{}.pkl'.format(quandl_id).replace('/','-')
    try:
        f = open(cache_path, 'rb')
        df = pickle.load(f)   
        print('Loaded {} from cache'.format(quandl_id))
    except (OSError, IOError) as e:
        print('Downloading {} from Quandl'.format(quandl_id))
        df = quandl.get(quandl_id, returns="pandas")
        df.to_pickle(cache_path)
        print('Cached {} at {}'.format(quandl_id, cache_path))
    return df


btc_usd_price_kraken = get_quandl_data('BCHARTS/KRAKENUSD')



exchanges = ['COINBASE','BITSTAMP','ITBIT']

exchange_data = {}

exchange_data['KRAKEN'] = btc_usd_price_kraken

for exchange in exchanges:
    exchange_code = 'BCHARTS/{}USD'.format(exchange)
    btc_exchange_df = get_quandl_data(exchange_code)
    exchange_data[exchange] = btc_exchange_df

def merge_dfs_on_column(dataframes, labels, col):

    series_dict = {}
    for index in range(len(dataframes)):
        series_dict[labels[index]] = dataframes[index][col]

    return pd.DataFrame(series_dict) 


btc_usd_datasets = merge_dfs_on_column(list(exchange_data.values()), 
list(exchange_data.keys()), 'Weighted Price')



def df_scatter(df, title, seperate_y_axis=False, y_axis_label='', 
scale='linear', initial_hide=False):

    label_arr = list(df)
    series_arr = list(map(lambda col: df[col], label_arr))

    layout = go.Layout(
        title=title,
        legend=dict(orientation="h"),
        xaxis=dict(type='date'),
        yaxis=dict(
            title=y_axis_label,
            showticklabels= not seperate_y_axis,
            type=scale
        )
    )

    y_axis_config = dict(
        overlaying='y',
        showticklabels=False,
        type=scale )

    visibility = 'visible'
    if initial_hide:
        visibility = 'legendonly'


    trace_arr = []
    for index, series in enumerate(series_arr):
        trace = go.Scatter(
            x=series.index, 
            y=series, 
            name=label_arr[index],
            visible=visibility
        )


        if seperate_y_axis:
            trace['yaxis'] = 'y{}'.format(index + 1)
            layout['yaxis{}'.format(index + 1)] = y_axis_config    
        trace_arr.append(trace)

    fig = go.Figure(data=trace_arr, layout=layout)
    py.plot(fig)



df_scatter(btc_usd_datasets, 'Bitcoin Price (USD) By Exchange')


btc_usd_datasets.replace(0, np.nan, inplace=True)


df_scatter(btc_usd_datasets, 'Bitcoin Price (USD) By Exchange')


btc_usd_datasets['avg_btc_price_usd'] = btc_usd_datasets.mean(axis=1)



btc_trace = go.Scatter(x=btc_usd_datasets.index, 
y=btc_usd_datasets['avg_btc_price_usd'])
py.plot([btc_trace])



def get_json_data(json_url, cache_path):

    try:        
        f = open(cache_path, 'rb')
        df = pickle.load(f)   
        print('Loaded {} from cache'.format(json_url))
    except (OSError, IOError) as e:
        print('Downloading {}'.format(json_url))
        df = pd.read_json(json_url)
        df.to_pickle(cache_path)
        print('Cached {} at {}'.format(json_url, cache_path))
    return df

# Helper Function that Generates Poloniex API HTTP requests
base_polo_url = 'https://poloniex.com/public? 
command=returnChartData&currencyPair={}&start={}&end={}&period={}'
start_date = datetime.datetime.strptime('2015-01-01', '%Y-%m-%d') # get 
data from the start of 2015
end_date = datetime.datetime.now() # up until today
pediod = 86400 # pull daily data (86,400 seconds per day)

def get_crypto_data(poloniex_pair):

    json_url = base_polo_url.format(poloniex_pair, start_date.timestamp(), end_date.timestamp(), pediod)
    data_df = get_json_data(json_url, poloniex_pair)
    data_df = data_df.set_index('date') 
    return data_df


altcoins = ['ETH','LTC','XRP','ETC','STR','DASH','SC','XMR','XEM']
altcoin_data = {}
for altcoin in altcoins:
    coinpair = 'BTC_{}'.format(altcoin)
    crypto_price_df = get_crypto_data(coinpair)
    altcoin_data[altcoin] = crypto_price_df

回答by abarnert

The timestampmethod was added in Python 3.3. So if you're using Python 2.0, or even 2.7, you don't have it.

timestamp方法是在 Python 3.3 中添加的。因此,如果您使用的是 Python 2.0,甚至 2.7,则您没有它。

There are backports of current datetimeto older Python versions on PyPI, but none of them seems to be official, or up-to-date; you might want to try searching for yourself.

datetimePyPI 上有当前到旧 Python 版本的向后移植,但它们似乎都不是官方的或最新的;您可能想尝试自行搜索。

There are also a number of third-party replacement libraries that add functionality that isn't in (2.x) datetime, including the ability to convert to Unix timestamps.

还有许多第三方替代库添加了 (2.x) 中没有的功能datetime,包括转换为 Unix 时间戳的能力。



You can just copy the function out of the source code from 3.3 or later:

您可以从 3.3 或更高版本的源代码中复制该函数

def timestamp(self):
    "Return POSIX timestamp as float"
    if self._tzinfo is None:
        s = self._mktime()
        return s + self.microsecond / 1e6
    else:
        return (self - _EPOCH).total_seconds()

… but you will have to modify things a bit to get them to work, because:

……但是您必须稍微修改一些东西才能使它们工作,因为:

  • _EPOCHis deleted at the end of the module.
  • The 3.x _EPOCHis a tz-aware object built with a proper UTC timezone, which you don't have in 2.x unless you're using a third-party library like pytz.
  • The _mktimemethod and _tzinfoattribute don't exist on 2.x datetime, so you need to simulate what they do as well.
  • _EPOCH在模块的末尾被删除。
  • 3.x_EPOCH是使用适当的 UTC 时区构建的 tz-aware 对象,除非您使用第三方库,否则在 2.x 中没有pytz
  • _mktime方法和_tzinfo属性上不存在2.X datetime,所以你需要模拟他们做了什么为好。

If you don't need the same function to work equally well for naive, GMT, and tz-aware datetimes, it won't be that hard, but it's still not quite trivial—and if you do need the full functionality, it's going to be more painful.

如果您不需要相同的功能来同样适用于 naive、GMT 和 tz-aware 日期时间,这不会那么难,但它仍然不是很简单——如果您确实需要完整的功能,它会继续要更痛苦。



Or it may be easier to port the equivalent code given in the docs.

或者移植文档中给出的等效代码可能更容易。

For aware datetimeinstances:

对于感知datetime实例:

(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

Of course you still don't have that timezone.utc, but for this purpose, you don't need a full timezone object; you can use an instance of the example UTCclass in the 2.x tzinfodocs.

当然,您仍然没有那个timezone.utc,但是为此,您不需要完整的时区对象;您可以UTC2.xtzinfo文档中使用示例类的实例。

… for naive:

……天真:

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

… or:

… 或者:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

Since you don't have aware datetimes, that last one is all you need.

由于您不知道日期时间,因此您只需要最后一个。



If your Python is old enough, timedeltamay not have a __div__method. In that case (if you haven't found a backport), you have to do division manually as well, by calling total_secondson each one, making sure at least one of them is a float, and dividing the numbers:

如果你的 Python 够老,timedelta可能没有__div__方法。在这种情况下(如果您还没有找到反向移植),您还必须手动进行除法,通过调用total_seconds每个,确保其中至少一个是浮点数,然后将数字相除:

timestamp = ((dt - datetime(1970, 1, 1)).total_seconds() / 
    float(timedelta(seconds=1).total_seconds()))

But in this particular case, it should be pretty obvious that the divisor is just going to be 1.0, and dividing by 1.0 is the same as doing nothing, so:

但在这种特殊情况下,很明显除数将是 1.0,除以 1.0 与什么都不做是一样的,所以:

timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

回答by Matias Cicero

As the other answers state, datetime.timestamp()was added on Python 3.3.

正如其他答案所述,datetime.timestamp()已添加到Python 3.3

To get a similar behavior on Python < 3.3, you need to use time.mktime():

要在 Python < 3.3 上获得类似的行为,您需要使用time.mktime()

import time

def to_seconds(date):
    return time.mktime(date.timetuple())

And then, instead of calling start_date.timestamp(), you just call to_seconds(start_date)

然后,而不是调用start_date.timestamp(),您只需调用to_seconds(start_date)

回答by jakub

The .timestamp()method was added in python version 3.3 [source], so you can't use .timestamp()in Python 2.

.timestamp()方法是在python 3.3 [源代码]中添加的,所以不能.timestamp()在Python 2中使用。

回答by Daniel B?ckenhoff

Comprehending an easy version independent use would be the following:

理解一个简单的版本独立使用如下:

import datetime
import sys
if sys.version_info[0] < 3 or sys.version_info[1] < 4:
    # python version < 3.3
    import time
    def timestamp(date):
        return time.mktime(date.timetuple())
else:
    def timestamp(date):
        return date.timestamp()

# Example usecase:
date = datetime.datetime.strptime('2015-01-01', '%Y-%m-%d')
print(timestamp(date))

回答by Mariano Ruiz

All you need in Python 2.x is to use the method time()from the timemodule, like this:

所有你在Python 2.x中需要的是使用的方法time()time模块,像这样:

>>> from time import time
>>> time()
1535495731.95094

It will give you the same than the timestamp()method from a datetimeobject from Python 3.x:

它将为您提供与来自 Python 3.xtimestamp()datetime对象的方法相同的方法:

>>> from datetime import datetime
>>> datetime.now().timestamp()
1535495993.949849

But this is only valid when you need the current timestamp, not any timestamp.

但这仅在您需要当前时间戳时才有效,而不是任何时间戳。

Official doc: https://docs.python.org/2/library/time.html#time.time

官方文档:https: //docs.python.org/2/library/time.html#time.time