Python时间日期函数与利用Pandas进行时间序列处理详解
一、Python时间日期函数
在Python中,datetime模块主要包含了以下类:
- date:日期对象,包含年、月、日等信息。
- time:时间对象,包含小时、分钟、秒、微秒等信息。
- datetime:日期时间对象,包含年、月、日、小时、分钟、秒、微秒等信息。
- timedelta:时间间隔对象,表示两个日期或者时间之间的差值。
这些类可以帮助我们在程序中操作时间日期,进行日期的计算、转换、比较等操作。下面是一些比较常见的用法示例:
# 导入datetime模块
from datetime import datetime, timedelta
# 定义日期时间
dt = datetime(2022, 12, 12, 20, 30, 0)
print(dt) # 2022-12-12 20:30:00
# 获取当前日期时间
now = datetime.now()
print(now) # 当前时间
# 时间转字符串
now_str = now.strftime('%Y-%m-%d %H:%M:%S')
print(now_str)
# 字符串转时间
str_to_time = datetime.strptime(now_str, '%Y-%m-%d %H:%M:%S')
print(str_to_time)
# 日期时间加减
delta = timedelta(days=1)
tomorrow = now + delta
print(tomorrow)
二、利用Pandas进行时间序列处理
Pandas是一款功能强大的数据分析库,其中一个重要的功能就是支持时间序列处理。Pandas中主要包含了以下时间序列相关的类和函数:
- Timestamp:时间戳,表示单个时间点。
- DatetimeIndex:时间索引,表示一组时间序列数据。
- Period:时间段,表示一段时间区间。
- PeriodIndex:时间段索引,表示一组时间段的数据。
以下是一些常见的Pandas时间序列用法示例:
# 导入Pandas库
import pandas as pd
# 创建时间序列数据
dates = pd.date_range('20220101', periods=7)
print(dates)
# 创建时间序列数据框
df = pd.DataFrame({'date': dates, 'value': [1, 2, 3, 4, 5, 6, 7]})
print(df)
# 将日期列设置为索引
df = df.set_index('date')
print(df)
# 选择时间序列数据
print(df['2022-01']) # 只选择2022年1月的数据
# 时间序列重采样
print(df.resample('W').sum()) # 每周重采样,求和
# 时间序列移动
print(df['value'].shift(1)) # 将数据整体向下移动一位
三、示例说明
示例1:日期时间计算
假设我们需要计算某个事件距离今天还有多少天,可以使用datetime模块中的timedelta来实现。具体代码如下:
from datetime import datetime
today = datetime.now()
event_day = datetime(2023, 1, 1)
delta = event_day - today
print(delta.days) # 输出距离事件还有多少天
运行结果为:375
示例2:时间序列处理
假设我们有一个时间序列数据框df,其中包含了日期和股票收盘价信息。现在我们需要对数据框进行重采样处理,统计每周的平均收盘价。具体代码如下:
import pandas as pd
# 生成时间序列数据
dates = pd.date_range(start='20220101', periods=100)
prices = [i + 10 for i in range(100)]
df = pd.DataFrame({'date': dates, 'price': prices})
# 将日期列设置为索引
df = df.set_index('date')
# 每周重采样,求平均值
df_week = df.resample('W').mean()
print(df_week)
运行结果为:
price
date
2022-01-01 14.500000
2022-01-08 20.500000
2022-01-15 27.500000
2022-01-22 34.500000
2022-01-29 41.500000
2022-02-05 48.500000
2022-02-12 55.500000
2022-02-19 62.500000
2022-02-26 69.500000
2022-03-05 76.500000
2022-03-12 82.357143
2022-03-19 89.500000
2022-03-26 96.500000
2022-04-02 99.500000