pandas Generation Time List

pandas Generation Time List

1. Generate a time period based on the beginning and end time

The pd.date_range(start, end, freq) freq** parameter is in English (M D H Min...). Combination of English and numerals. D denotes one day, M denotes January as 20D denotes 20 days, and 5M denotes 5 months.

#Generate 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')

2. Generate the time period pd.date_range (date string, periods=5, freq='T') from the start to the back.

periods: period length, integer type
freq: unit of time. Month, day, hour and second. M D H...

import pandas as pd 
#20171231 12:50 time point to start, the generation of intervals with the month as the interval, the length of 5 time periods 
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')

3. Generate time intervals forward (backward) according to a given time point

pd.bdate_range(end,periods,freq) starts at the end time point and generates a period-period time series forward in freq units

pd.bdate_range(start,periods,freq) starts at the start time point and generates a time series with periods backwards in freq units

#Five days ahead 
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')

#Five days back 
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')

4. Time list in specified time format

The incoming date format can also be modified. freq parameter can be added to the pd.date_range function. The default is'D', which indicates the day.

import pandas as pd
def get_date_list(begin_date,end_date):
  date_list = [x.strftime('%Y-%m-%d') for x in list(pd.date_range(start=begin_date, end=end_date))]
  return date_list

# Testable
print(get_date_list('2018-06-01','2018-06-08'))

#  ['2018-06-01', '2018-06-02', '2018-06-03', '2018-06-04', '2018-06-05', '2018-06-06', '2018-06-07', '2018-06-08']

Keywords: Python

Added by kinadian on Thu, 10 Oct 2019 02:06:21 +0300