pandas “时间戳”对象没有“时间戳”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37945430/
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-09-14 01:25:58  来源:igfitidea点击:

'Timestamp' object has no attribute 'timestamp'

pythonpandastimestamp

提问by user6162407

I'm following a course where I have to convert a date to a unix timestamp.

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

import pandas as pd

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

class 'pandas.tslib.Timestamp'

类'pandas.tslib.Timestamp'

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

AttributeError: 'Timestamp' object has no attribute 'timestamp'

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

回答by Phil Sheard

You don't actually ask a question (tip for next time: be more explicit), but I assume you want an epoch / Unix timestamp from a Pandas Timestamp object.

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

If you use the pandas.tslib.Timestamp.valuemethod, you'll return the timestamp in microseconds (1/1,000,000 second):

如果您使用该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

If you prefer you can simply divide by 1000 to get milliseconds or 1000000 to get whole seconds, eg:

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

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

回答by MaxU

IIUC, you can do it this way:

IIUC,你可以这样做:

generate sample DF with datetime dtype

使用 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

convert datetime to UNIX timestamp

将日期时间转换为 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