Pandas时间序列处理:日期与时间

一、基础概念

1. 时间戳(Timestamp)

时间戳表示一个具体的时刻,例如2023年1月1日12点整。Pandas中的Timestamp对象可以精确到纳秒级别。

2. 时间间隔(Timedelta)

时间间隔表示两个时间戳之间的差值,例如1小时、5分钟等。Timedelta对象用于表示这种差值。

3. 周期(Period)

周期表示一段时间范围内的固定频率,例如每月的第一天、每季度的第一个月等。Period对象用于表示这种周期性的时间段。

二、常见问题及解决方案

1. 日期格式转换

问题描述:在实际应用中,日期数据往往以字符串形式存在,需要将其转换为Pandas可识别的时间戳格式。 解决方案:使用pd.to_datetime()函数可以轻松实现字符串到时间戳的转换。该函数支持多种日期格式,并且可以通过参数format指定特定的格式。

import pandas as pd

# 示例数据
date_str = '2023-01-01'

# 转换为时间戳
timestamp = pd.to_datetime(date_str)
print(timestamp)

# 指定格式转换
date_str_custom_format = '01/01/2023'
timestamp_custom_format = pd.to_datetime(date_str_custom_format, format='%d/%m/%Y')
print(timestamp_custom_format)
 
 

2. 处理缺失值

问题描述:在时间序列数据中,可能会遇到缺失的日期或时间信息。 解决方案:可以使用pd.NaT(Not a Time)来表示缺失的时间戳,并结合fillna()方法填充缺失值。

# 创建包含缺失值的时间序列
dates_with_na = ['2023-01-01', None, '2023-01-03']
ts_with_na = pd.to_datetime(dates_with_na)
print(ts_with_na)

# 填充缺失值
filled_ts = ts_with_na.fillna(pd.Timestamp('2023-01-02'))
print(filled_ts)
 
 

3. 时间间隔计算

问题描述:需要计算两个时间戳之间的差值。 解决方案:直接相减两个Timestamp对象即可得到Timedelta对象。

# 计算时间间隔
start_time = pd.Timestamp('2023-01-01 12:00:00')
end_time = pd.Timestamp('2023-01-01 14:30:00')
time_diff = end_time - start_time
print(time_diff)
 
 

4. 重采样

问题描述:有时需要将高频数据聚合为低频数据,或者将低频数据扩展为高频数据。 解决方案:使用resample()方法可以方便地对时间序列数据进行重采样。

# 创建时间序列数据
index = pd.date_range('2023-01-01', periods=10, freq='D')
data = pd.Series(range(10), index=index)

# 按周重采样并求和
weekly_data = data.resample('W').sum()
print(weekly_data)
 
 

三、常见报错及解决方法

1. ParserError

问题描述:当使用pd.to_datetime()时,如果提供的日期字符串不符合预期格式,会抛出ParserError。 解决方案:确保输入的日期字符串格式正确,或者使用errors='coerce'参数将无法解析的值转换为NaT

# 可能引发ParserError的代码
invalid_date_str = 'invalid-date'
try:
    timestamp = pd.to_datetime(invalid_date_str)
except pd.errors.ParserError:
    print("日期格式错误")

# 使用errors='coerce'参数
timestamp_coerce = pd.to_datetime(invalid_date_str, errors='coerce')
print(timestamp_coerce)
 
 

2. OutOfBoundsDatetime

问题描述:当尝试创建超出Pandas支持范围的时间戳时,会抛出OutOfBoundsDatetime异常。 解决方案:检查输入的时间是否在合理范围内,或者调整业务逻辑以避免这种情况。

# 可能引发OutOfBoundsDatetime的代码
out_of_bounds_date = '9999-12-31'
try:
    timestamp = pd.Timestamp(out_of_bounds_date)
except pd._libs.tslibs.np_datetime.OutOfBoundsDatetime:
    print("时间超出支持范围")
posted @   alloutlove  阅读(124)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示