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

yipeiwu_com7年前Python基础

创建时间序列

函数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'

主要的入参解析:

  • start: 开始时刻,可以是字符串或者datetime类型的值。默认None。
  • end: 结束时刻,可以是字符串或者datetime类型的值,如果指定了长度,即periods,则可不设置。默认None。
  • periods: 时序的长度,整型类型。如果有end,可不设置。默认None。
  • freq: 时序生成的频率,即每隔多少时刻生成一个时序点。字符串类型或者DateOffset类型。默认'D',即天粒度,见上述代码输出。
  • tz: 时区,字符串类型。默认None。
  • normalize: bool类型,没用过,不知道干啥的。
  • name: 设置时序的名称,字符串类型,默认None。
  • closed: 是否包含两边的值。默认None,即两边都保留。

其中,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常用的参数:

  • months,设置月。
  • days,设置天。
  • years,设置年。
  • hours,设置小时。
  • minutes,设置分钟。
  • seconds,设置秒。

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

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

输出为:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python随机生成信用卡卡号的实现方法

本文实例讲述了Python随机生成信用卡卡号的实现方法。分享给大家供大家参考。具体分析如下: 这段Python代码根据信用卡卡号产生规则随机生成信用卡卡号,是可以通过验证的,仅供学习参考...

对python使用http、https代理的实例讲解

在国内利用Python从Internet上爬取数据时,有些网站或API接口被限速或屏蔽,这时使用代理可以加速爬取过程,减少请求失败,Python程序使用代理的方法主要有以下几种: (1)...

Python编程实现从字典中提取子集的方法分析

本文实例讲述了Python编程实现从字典中提取子集的方法。分享给大家供大家参考,具体如下: 首先我们会想到使用字典推导式(dictionary comprehension)来解决这个问题...

Python学习笔记之Break和Continue用法分析

本文实例讲述了Python学习笔记之Break和Continue用法。分享给大家供大家参考,具体如下: Python 中的Break 和 Continue break:控制何时循环...

详解Python2.x中对Unicode编码的使用

我确定有很多关于Unicode和Python的说明,但为了方便自己的理解使用,我还是打算再写一些关于它们的东西。   字节流 vs Unicode对象 我们先来用Python定...