AttributeError:“ Timestamp”对象没有属性“ timestamp”

use*_*212 5 python time timestamp

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

Train ['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())
Run Code Online (Sandbox Code Playgroud)

我得到这个错误:

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'
Run Code Online (Sandbox Code Playgroud)

ntg*_*ntg 10

to_datetime 似乎已被弃用。使用to_pydatetime(),而不是...


pat*_*ffe 5

您正在寻找datetime.timestamp(),它是在 Python 3.3 中添加的。Pandas 本身不参与其中。

NB .timestamp()会将原始时间戳本地化为计算机的 UTC 偏移量。相反,此答案中的建议与时区无关。

由于 pandas在内部使用纳秒(numpy datetime64[ns] ),因此即使使用 Python 2,您也应该能够执行此操作:

Train['timestamp'] = pd.to_datetime(Train['date']).value / 1e9
Run Code Online (Sandbox Code Playgroud)

或者更明确地使用这样的东西(来自日期时间文档):

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)
Run Code Online (Sandbox Code Playgroud)


小智 4

to_datetime 方法将返回一个TimeStamp实例。我不确定您希望通过 lambda 函数完成什么,但您似乎正在尝试将某些对象转换为TimeStamp.

尝试删除应用部分,使其看起来像这样:

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