处理时间序列

datetime模块

Python基本的日期与时间功能都在标准库的datetime模块中。

主要的类

可对date、time、datetime三种时间模式进行单独管理
datetime.date() 处理日期(年月日)
datetime.time() 处理时间(时分秒、毫秒)
datetime.datetime() 处理日期+时间
datetime.timedelta() 处理时段(时间间隔)

 

获取当前时间

获取今天的日期
datetime.date.today()
datetime.datetime.now()

修改日期格式
使用strftime格式化
datetime.datetime.isoformat()

 

 

时间戳

时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总秒数

将日期转换成时间戳

timetuple函数 : 将时间转换成struct_time格式
time.mktime函数 : 返回用秒数来表示时间的浮点数

将时间戳转换成日期
datetime.date.fromtimestamp()

 

 

时间上的加减法

timedelta()方法
表示两个时间点的间隔

 

Pandas

Pandas 所有关于日期与时间的处理方法全部都是通过Timestamp 对象实现的,它利用numpy.datetime64 的有效存储和向量化接口将datetime 和dateutil 的易用性有机结合起来。

Pandas有一些功能非常强大的日期、时间、带时间索引数据的处理工具。
• 时间戳    Timestamp类型,对应的索引数据结构是DatetimeIndex。
• 时间间隔与周期    Period类型,对应的索引数据结构是PeriodIndex。
• 时间增量(time delta)或持续时间(duration)  Timedelta类型,对应的索引数据结构是TimedeltaIndex。

 

 

用时间作索引

Pandas 时间序列工具非常适合用来处理带时间戳的索引数据。

 

 

有规律的时间序列

pd.date_range() 可以处理时间戳
pd.period_range() 可以处理周期
pd.timedelta_range() 可以处理时间间隔

 

posted on 2021-10-12 09:12  trp  阅读(110)  评论(0编辑  收藏  举报

导航