33. Pandas的时间序列数据-Timestamp

在pandas里可以使用pandas.tslib.Timestamp类来实现时间序列,本章就Timestamp进行展开,了解该类的基本使用。

from pandas.tslib import Timestamp
cur0 = Timestamp("2018-12-26 17:30:36")
print cur0
cur0 = Timestamp("17:30:36")
print cur0

程序执行结果:

2018-12-26 17:30:36
2018-12-16 17:30:36

使用pandas的timedelta模块实现时间的间隔。

from pandas.tslib import Timestamp
cur0 = Timestamp("2018-12-26 17:30:36")
print cur0
cur0 = Timestamp("17:30:36")
print cur0
import pandas as pd
from datetime import datetime
cur1 = cur0 + pd.Timedelta(days = 1)
print cur1
cur2 = datetime(2018,12,16,17,30, 36) + pd.Timedelta(days = 1)
print cur2

程序执行结果:

2018-12-26 17:30:36 # cur0
2018-12-16 17:30:36 # cur0
2018-12-17 17:30:36 # cur1
2018-12-17 17:30:36 # cur2

利用pandas的timedelta构造时间序列数据:

import numpy as np
import pandas as pd
b = datetime(2018,12,16, 17,30,55)
vi = np.random.randn(60)
ind = []
for x in range(60):
    bi = b + pd.Timedelta(minutes = x)
    ind.append(bi)
ts = pd.Series(vi, index = ind)
print ts[:5]

程序的执行结果:

2018-12-16 17:30:55   -0.816316
2018-12-16 17:31:55   -0.914680
2018-12-16 17:32:55   -0.304760
2018-12-16 17:33:55   -1.339267
2018-12-16 17:34:55    1.578459
dtype: float64

感谢Klang(金浪)智能数据看板klang.org.cn鼎力支持!