pandas.date_range()用于生成指定长度的DatatimeIndex:
1)默认情况下,date_range会按着时间间隔为天的方式生成从给定开始到结束时间的时间戳数组;
2)如果只指定开始或结束时间,还需要periods标定时间长度。
import pandas as pd
pd.date_range('2017-6-20','2017-6-27')
DatetimeIndex(['2017-06-20', '2017-06-21', '2017-06-22', '2017-06-23',
'2017-06-24', '2017-06-25', '2017-06-26', '2017-06-27'],
dtype='datetime64[ns]', freq='D')
pd.date_range('2017-6-20 12:59:30','2017-6-27')
DatetimeIndex(['2017-06-20 12:59:30', '2017-06-21 12:59:30',
'2017-06-22 12:59:30', '2017-06-23 12:59:30',
'2017-06-24 12:59:30', '2017-06-25 12:59:30',
'2017-06-26 12:59:30'],
dtype='datetime64[ns]', freq='D')
pd.date_range('2017-6-20 12:59:30',periods = 8)
DatetimeIndex(['2017-06-20 12:59:30', '2017-06-21 12:59:30',
'2017-06-22 12:59:30', '2017-06-23 12:59:30',
'2017-06-24 12:59:30', '2017-06-25 12:59:30',
'2017-06-26 12:59:30', '2017-06-27 12:59:30'],
dtype='datetime64[ns]', freq='D')
pd.date_range('2017-6-20 12:59:30',periods = 8, normalize = True)
DatetimeIndex(['2017-06-20', '2017-06-21', '2017-06-22', '2017-06-23',
'2017-06-24', '2017-06-25', '2017-06-26', '2017-06-27'],
dtype='datetime64[ns]', freq='D')
pandas中的频率是由一个基础频率(M、H)也可以是(Hour、Minute、h、min等)
pd.date_range('2017-6-27',periods = 7,freq = '1h30min')
DatetimeIndex(['2017-06-27 00:00:00', '2017-06-27 01:30:00',
'2017-06-27 03:00:00', '2017-06-27 04:30:00',
'2017-06-27 06:00:00', '2017-06-27 07:30:00',
'2017-06-27 09:00:00'],
dtype='datetime64[ns]', freq='90T')
pd.date_range('2017-6-27',periods = 7,freq = 'M')
DatetimeIndex(['2017-06-30', '2017-07-31', '2017-08-31', '2017-09-30',
'2017-10-31', '2017-11-30', '2017-12-31'],
dtype='datetime64[ns]', freq='M')
pd.date_range('2017-6-27',periods = 7,freq = 'd')
DatetimeIndex(['2017-06-27', '2017-06-28', '2017-06-29', '2017-06-30',
'2017-07-01', '2017-07-02', '2017-07-03'],
dtype='datetime64[ns]', freq='D')
pd.date_range('2017-6-27',periods = 7,freq = 'H')
DatetimeIndex(['2017-06-27 00:00:00', '2017-06-27 01:00:00',
'2017-06-27 02:00:00', '2017-06-27 03:00:00',
'2017-06-27 04:00:00', '2017-06-27 05:00:00',
'2017-06-27 06:00:00'],
dtype='datetime64[ns]', freq='H')
别名 | 偏移量 | 说明 |
---|---|---|
D/d | Day | 每日历日 |
B | BusinessDay | 每工作日 |
H/h | Hour | 每小时 |
T或min | Minute | 每分 |
S | Secend | 每秒 |
L或ms | Milli | 每毫秒(每千分之一秒) |
U | Micro | 每微秒(即百万分之一秒) |
M | MonthEnd | 每月最后一个日历日 |
BM | BusinessDayEnd | 每月最后一个工作 |
上表只展示了部分!
pd.date_range('2017-06-01','2017-07-31',freq='WOM-3FRI')
DatetimeIndex(['2017-06-16', '2017-07-21'], dtype='datetime64[ns]', freq='WOM-3FRI')