亲宝软件园·资讯

展开

python pandas时序处理相关功能详解

人气:0

创建时间序列

函数pd.date_range()

根据指定的范围,生成时间序列DatetimeIndex,每隔元素的类型为Timestamp。该函数应用较多。

ts = pd.date_range('2017-09-01', periods=10, freq='d', normalize=False)
ts

输出为:

DatetimeIndex(['2017-09-01', '2017-09-02', '2017-09-03', '2017-09-04',
'2017-09-05', '2017-09-06', '2017-09-07', '2017-09-08',
'2017-09-09', '2017-09-10'],
dtype='datetime64[ns]', freq='D'

主要的入参解析:

其中,freq的取值可以为如下的符号表示间隔,可以结合符号和数字,如'3d',表示每隔三天记录一个时间点。大小写都可以。

B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds

字符串转换为时间戳

pd.to_datetime() 函数可以将表示时间的字符串转换位TimeStamp。

pd.to_datetime('2017-09-01')

输出为:

Timestamp('2017-09-01 00:00:00')

常用的参数:

format: 用来设置字符串的格式,默认如上所示。

时间戳的加减
有时候需要将时间进行增减,可以使用类型:DateOffset。

pd.to_datetime('2017-09-01') + pd.DateOffset(days=10) 

输出为:

Timestamp('2017-09-11 00:00:00')

DateOffset常用的参数:

以上可以同时设置,组合使用。

pd.to_datetime('2017-09-01') + pd.DateOffset(seconds=10, days = 10)

输出为:

Timestamp('2017-09-11 00:00:10')
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论