目录
第一部分:pandas时间序列
一.python中的时间日期
datetime模块和timedelta模块
1.datetime(2016, 3, 20, 8, 30).strftime('%Y-%m-%d %H:%M:%S')
----strftime从time格式转化成字符串str格式,strftime()括号内为具体的字符串形式。
等价于datetime.strftime(datetime(2016, 3, 20, 8, 30),'%Y-%m-%d %H:%M:%S')
2.datetime.strptime('2016-03-20 09:30', '%Y-%m-%d %H:%M')
----strptime从字符串str格式转化成time格式,括号内为待转换的字符串形式。
二.pandas中的时间日期
1.固定时刻timestamp:pandas会将datetime转换成timestamp形式。
日期序列:利用data_range()函数
1)pd.date_range('20160320', '20160331')
----给出范围
2)pd.date_range(start='20160320', periods=10)
----给出起始日期和周期
3)pd.date_range(start='20160320', periods=10, freq='4H')
----给出起始、周期和时间频率
2.固定时期period:
1)p1 = pd.Period(2016, freq='M')
----默认.Period()表示以年为周期
时期序列:利用period_range()函数
2)时期的频率转换:asfreq()
A-DEC: 以12月份作为结束的年时期
A-NOV: 以11月份作为结束的年时期
Q-DEC: 以12月份作为结束的季度时期
例1:将以年为单位、十二月为结尾的日期转换成以月为单位的时期
p = pd.Period('2016', freq='A-DEC')
p.asfreq('M', how='start'
out[]:Period('2016-01', 'M')
p.asfreq('M', how='end')
out[]:Period('2016-12', 'M')
例2:季度时期的表示:
p = pd.Period('2016Q4', 'Q-JAN')
----表示季度时期,以一月份为结尾,2016Q4指的是2015年11月–2016年1月
例3:
# 获取该季度倒数第二个工作日下午4点的时间戳
p4pm = (p.asfreq('B', how='end') - 1).asfreq('T', 'start') + 16 * 60
3.timestamp和period转换:to_period()和to_timestamp
ts = pd.Series(np.random.randn(5), index = pd.date_range('2016-12-29', periods=5, freq='D'))
ts
out[]:
2016-12-29 -0.110462
2016-12-30 -0.265792
2016-12-31 -0.382456
2017-01-01 -0.036111
2017-01-02 -1.029658
Freq: D, dtype: float64
pts = ts