AttributeError:'Timestamp'对象没有属性'timestamp

时间:2016-09-11 10:08:37

标签: python time timestamp

在将panda对象转换为时间戳时,我面临着这个奇怪的问题。

训练['date']值就像01/05/2014,我试图将其转换为linuxtimestamp。

我的代码:

Train = pd.read_csv("data.tsv", sep='\t') # use TAB as column separator
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())

我收到了这个错误:

Traceback (most recent call last):
  File "socratis.py", line 11, in <module>
    Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
  File "/home/ubuntu/.local/lib/python2.7/site-packages/pandas/core/series.py", line 2220, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/src/inference.pyx", line 1088, in pandas.lib.map_infer (pandas/lib.c:62658)
  File "socratis.py", line 11, in <lambda>
    Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
AttributeError: 'Timestamp' object has no attribute 'timestamp'

3 个答案:

答案 0 :(得分:1)

方法to_datetime将返回TimeStamp个实例。我不确定你希望通过lambda函数完成什么,但看起来你正试图将一些对象转换为TimeStamp

尝试删除“应用”部分,使其如下所示:

Train['timestamp'] = pd.to_datetime(Train['date'])

答案 1 :(得分:1)

您正在寻找在Python 3.3中添加的datetime.timestamp()。熊猫本身并没有参与其中。

  

N.B。 .timestamp()会将天真时间戳本地化为计算机的UTC偏移量。相反,这个答案中的建议与时区无关。

自pandas uses nanoseconds internally(numpy datetime64[ns])以来,即使使用Python 2,你也应该能够做到这一点:

Train['timestamp'] = pd.to_datetime(Train['date']).value / 1e9

或者更明确地用这样的东西(来自datetime docs):

import pandas as pd
from datetime import datetime, timedelta

def posix_time(dt):
    return (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

Train['timestamp'] = pd.to_datetime(Train['date']).apply(posix_time)

答案 2 :(得分:1)

to_datetime seems to be deprecated.改用to_pydatetime() ...