【问题标题】:'Timestamp' object has no attribute 'timestamp'“时间戳”对象没有属性“时间戳”
【发布时间】:2016-06-21 22:30:19
【问题描述】:

我正在学习必须将日期转换为 unix 时间戳的课程。

import pandas as pd

df = pd.read_csv('file.csv')
print type(df.iloc[-1].name)

类'pandas.tslib.Timestamp'

ts = df.iloc[-1].name.timestamp()

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

【问题讨论】:

  • 似乎Timestamp 类不提供timestamp() 方法。应该这样吗?
  • 你想做什么?
  • 嗨 - 我的回复或@MaxU 的回复是否有助于解决您的问题?如果是这样,如果您可以将问题标记为已回答,那就太好了。

标签: python pandas timestamp


【解决方案1】:

您实际上并没有提出问题(下次提示:更明确),但我假设您想要来自 Pandas Timestamp 对象的 epoch / Unix 时间戳。

如果您使用pandas.tslib.Timestamp.value 方法,您将以微秒(1/1,000,000 秒)为单位返回时间戳:

In [1]: import pandas as pd

In [2]: date_example = pd.to_datetime("2016-06-21")

In [3]: type(date_example)
Out[3]: pandas.tslib.Timestamp

In [4]: date_example.value
Out[4]: 1466467200000000000

如果您愿意,您可以简单地除以 1000 得到毫秒或 1000000 得到整秒,例如:

In [5]: date_example.value / 1000000
Out[5]: 1466467200000

【讨论】:

    【解决方案2】:

    IIUC,你可以这样做:

    使用 datetime dtype 生成样本 DF

    In [65]: x = pd.DataFrame({'Date': pd.date_range('2016-01-01', freq='5D', periods=5)})
    
    In [66]: x
    Out[66]:
            Date
    0 2016-01-01
    1 2016-01-06
    2 2016-01-11
    3 2016-01-16
    4 2016-01-21
    

    将日期时间转换为 UNIX 时间戳

    In [67]: x.Date.astype(np.int64) // 10**9
    Out[67]:
    0    1451606400
    1    1452038400
    2    1452470400
    3    1452902400
    4    1453334400
    Name: Date, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      相关资源
      最近更新 更多