我正在遵循一门课程,我必须将日期转换为unix时间戳。
import pandas as pd
df = pd.read_csv('file.csv')
print type(df.iloc[-1].name)
class'pandas.tslib.timestamp'
ts = df.iloc[-1].name.timestamp()
attributeError:'timestamp'对象没有属性'timestamp'
您实际上没有问一个问题(下一次:更明确),但是我假设您想要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
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
将DateTime转换为UNIX TIMESTAMP
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