Python pandas date_range with sampling assigned to each day separately

Viewed 75

I want to create date range between specific dates with a certain sampling within each day, but each day should start at midnight:

['2017-01-01 00:00:00', '2017-01-01 05:00:00','2017-01-01 10:00:00', '2017-01-01 15:00:00', '2017-01-01 20:00:00', '2017-01-02 00:00:00', '2017-01-02 05:00:00' ...]

Of course, in default pd.date_range(date1,date2,freq='5H') gives the output:

['2017-01-01 00:00:00', '2017-01-01 05:00:00', '2017-01-01 10:00:00', '2017-01-01 15:00:00', '2017-01-01 20:00:00', '2017-01-02 01:00:00', '2017-01-02 06:00:00', ..]

Any idea of how to handle this issue? Thank you!

1 Answers

Create hours range and then filter by modulo 5 by hours in indexing:

date1= '2017-01-01'
date2= '2017-01-04'

r =  pd.date_range(date1,date2,freq='H')
r = r[r.hour % 5 == 0]
print (r)
DatetimeIndex(['2017-01-01 00:00:00', '2017-01-01 05:00:00',
               '2017-01-01 10:00:00', '2017-01-01 15:00:00',
               '2017-01-01 20:00:00', '2017-01-02 00:00:00',
               '2017-01-02 05:00:00', '2017-01-02 10:00:00',
               '2017-01-02 15:00:00', '2017-01-02 20:00:00',
               '2017-01-03 00:00:00', '2017-01-03 05:00:00',
               '2017-01-03 10:00:00', '2017-01-03 15:00:00',
               '2017-01-03 20:00:00', '2017-01-04 00:00:00'],
              dtype='datetime64[ns]', freq=None)
    
Related