python中利用pandas按照时间段生成时间列表

本文详细介绍Pandas库中处理时间序列数据的各种方法,包括生成时间范围、改变时间间隔、统一日期格式及提取指定日期数据等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取当前时间,并返回年月日规范格式。形如 2017-01-04

常用的方法有:

pd.date_range() 生成一个时间段
pd.bdate_range() 生成一个时间段,跟date_range()不同,可见下面代码
df.asfreq() 生成以一定时间间隔的序列
  • 根据始末时间生成时间段

pd.date_range(start, end, freq) 生成一个时间段

freq参数由英文(M D H Min 。。。)、英文数字结合。D表示一天,M表示一月如20D表示20天,5M表示5个月。

#生成20171011-20171030 
pd.date_range('20171011', '20171030',freq='5D') 
DatetimeIndex(['2017-10-11', '2017-10-16', '2017-10-21', '2017-10-26'], dtype='datetime64[ns]', freq='5D')
  • 根据起始向后生成时间段

pd.date_range(日期字符串, periods=5, freq='T') 生成一个时间段

periods 时间段长度,整数类型 

freq 时间单位。月日时分秒。M D H ...

复制代码

import pandas as pd 
#20171231 12:50时间点开始,生成以月为间隔,长度为5的时间段 
tm_rng = pd.date_range('20171231 12:50',periods=5,freq='M') 
 
print(type(tm_rng)) 
DatetimeIndex(['2017-12-31 12:50:00', '2018-01-31 12:50:00','2018-02-28 12:50:00', '2018-03-31 12:50:00',
 
print(tm_rng)
<class 'pandas.core.indexes.datetimes.DatetimeIndex'> 
'2018-04-30 12:50:00'],dtype='datetime64[ns]', freq='M')

复制代码

  • 根据给定时间点向前(向后)生成时间段

pd.bdate_range(end,periods,freq) 根据end时间点开始,以freq为单位,向前生成周期为period的时间序列

pd.bdate_range(start,periods,freq) 根据start时间点开始,以freq为单位,向后生成周期为period的时间序列

复制代码

#向前5天 
print(pd.bdate_range(end='20180101',periods=5,freq='D'))
DatetimeIndex(['2017-12-28', '2017-12-29', '2017-12-30', '2017-12-31','2018-01-01'],dtype='datetime64[ns]', freq='D')

#向后5天 
print(pd.bdate_range(start='20180101',periods=5,freq='D'))
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04','2018-01-05'],dtype='datetime64[ns]', freq='D')

复制代码

改变时间间隔

对dateframe或者series对象操作,更改对象中时间的时间间隔。
dateframe.asfreq(freq='时间间隔',method='填充方式',fill_value='对Nan值进行填充') 
freq格式:M D H Min 。。。与数字结合。如20D表示20天,5M表示5个月。 
method:有pad、backfill两种填充方式
fill_value:缺失值更改为fill_value的值。

复制代码

#改变时间间隔,以20天为间隔 
tm_series.asfreq('20D',method='pad')
2017-12-31 12:50:00    0
2018-01-20 12:50:00    0
2018-02-09 12:50:00    1
2018-03-01 12:50:00    2
2018-03-21 12:50:00    2
2018-04-10 12:50:00    3
2018-04-30 12:50:00    4
Freq: 20D, dtype: int64

#改变时间间隔,以20天为间隔 
tm_series.asfreq('20D',method='backfill')
2017-12-31 12:50:00    0
2018-01-20 12:50:00    1
2018-02-09 12:50:00    2
2018-03-01 12:50:00    3
2018-03-21 12:50:00    3
2018-04-10 12:50:00    4
2018-04-30 12:50:00    4
Freq: 20D, dtype: int64

#改变时间间隔,以100小时为间隔 
tm_series.asfreq('100H')
2017-12-31 12:50:00    0.0
2018-01-04 16:50:00    NaN
2018-01-08 20:50:00    NaN
2018-01-13 00:50:00    NaN
.....
2018-04-10 12:50:00    NaN
2018-04-14 16:50:00    NaN
2018-04-18 20:50:00    NaN
2018-04-23 00:50:00    NaN
2018-04-27 04:50:00    NaN
Freq: 100H, dtype: float64

#改变时间间隔,以100小时为间隔 
tm_series.asfreq('100H',fill_value='缺失值')
2017-12-31 12:50:00      0
2018-01-04 16:50:00    缺失值
2018-01-08 20:50:00    缺失值
2018-01-13 00:50:00    缺失值
.....
2018-04-14 16:50:00    缺失值
2018-04-18 20:50:00    缺失值
2018-04-23 00:50:00    缺失值
2018-04-27 04:50:00    缺失值
Freq: 100H, dtype: object

复制代码

  • 可以统一日期格式

复制代码

data = pd.Series(['May 20, 2017','2017-07-12','20170930','2017/10/11','2017 12 11']) 
 
pd.to_datetime(data)
0   2017-05-20
1   2017-07-12
2   2017-09-30
3   2017-10-11
4   2017-12-11
dtype: datetime64[ns]

复制代码

  • 提取指定日期的数据

如下tm_rng是以5小时时间间隔,生成了20个数据。我们只要2018-01-02的数据。对Series或Dataframe都可以使用日期字符串操作,选取指定时间范围的数据。

复制代码

import pandas as pd 
import numpy as np
 
tm_rng = pd.date_range('2017-12-31 12:00:00',periods=20,freq='5H') 
tm_series = pd.Series(np.random.randn(len(tm_rng)), index=tm_rng) 
print(type(tm_series)) 
 
print(tm_series)
<class 'pandas.core.series.Series'> 
2017-12-31 12:00:00    0.618465
2017-12-31 17:00:00   -0.963631
2017-12-31 22:00:00   -0.782348
.....
2018-01-04 06:00:00   -0.681123
2018-01-04 11:00:00   -0.710626
Freq: 5H, dtype: floa64

#我们只要tm_series中是2018-01-02的数据 
tm_series['2018-01-02']
2018-01-02 04:00:00    0.293941
2018-01-02 09:00:00   -1.437363
2018-01-02 14:00:00   -0.527275
2018-01-02 19:00:00    1.140872
Freq: 5H, dtype: float64

#我们要2018年的数据,结果全保留 
tm_series['2018']
2018-01-01 03:00:00   -0.363019
2018-01-01 08:00:00    0.426922
2018-01-01 13:00:00   -1.118425
2018-01-01 18:00:00    0.956300
.....
2018-01-03 20:00:00   -1.967839
2018-01-04 01:00:00   -0.654029
2018-01-04 06:00:00   -0.681123
2018-01-04 11:00:00   -0.710626
Freq: 5H, dtype: float64
dft = pd.DataFrame(np.random.randn(len(tm_rng)), index=tm_rng) 
 
print(type(dft)) 
print(dft)
<class 'pandas.core.frame.DataFrame'>
                            
2017-12-31 12:00:00  0.213331
2017-12-31 17:00:00  1.920131
2017-12-31 22:00:00 -1.608645
2018-01-01 03:00:00 -0.226439
2018-01-01 08:00:00 -0.558741
.....
 
2018-01-03 20:00:00  0.866822
2018-01-04 01:00:00 -0.361902
2018-01-04 06:00:00  0.902717
2018-01-04 11:00:00 -0.431569

#对dataframe中的时间操作,只要2018-01-04日的数据 
print(type(dft['2018-01-04'])) 
print(dft['2018-01-04'])
<class 'pandas.core.frame.DataFrame'>
                            
2018-01-04 01:00:00 -0.361902
2018-01-04 06:00:00  0.902717
2018-01-04 11:00:00 -0.431569
要使用 Python 生成指定时间段内的时间序列,可以利用 `datetime` 和 `pandas` 这两个库的功能。这里,我们将创建一个从2008年至2022年的每年6月至10月的第一个日期列表。 ### 步骤一:导入所需模块 ```python from datetime import datetime, timedelta import pandas as pd ``` ### 步骤二:定义起始与结束年份以及月份范围 ```python start_year = 2008 end_year = 2022 months = range(6, 11) ``` ### 步骤三:生成每年特定月份的第一天并构建时间序列 ```python dates_list = [] for year in range(start_year, end_year + 1): for month in months: start_of_month = datetime(year, month, 1) dates_list.append(start_of_month) # 创建时间序列 DataFrame time_series = pd.DataFrame({'date': dates_list}) ``` ### 步骤四:将时间序列转换为日期格式,并设置为索引 ```python time_series['date'] = pd.to_datetime(time_series['date']) time_series.set_index('date', inplace=True) ``` 这样我们就得到了一个时间序列数据帧(DataFrame),其中行示每年的6至10月的第一天,列只有一项,即日期列已转换为日期格式并且设为索引。这适用于绘制折线图或其他图时,以这些日期作为横轴。 --- ## 相关问题: 1. 如何进一步对这个时间序列数据进行过滤操作,比如仅保留某个特定区间内的数据? 2. 可以使用哪种图形库来可视化这些时间序列数据,以便更直观地展示数据变化趋势? 3. 当时间序列数据包含不完整月份或非连续月份时,应该如何调整代码以保持时间序列的连续性?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值