Skip to content
Advertisement

Creating a range of dates and specific time in Python

I’m trying to define a range that begins at hour 2 rather than hour 0, but the following code returns all ranges beginning/ending at hour 0.

import pandas as pd
start_date = '2005-1-1 02:00:00'
end_date = '2005-5-1 02:00:00'

date_range = pd.bdate_range(start=start_date, end=end_date, freq='H')
print(date_range)

The output for the code above is the following, but I want it to begin at specific hour (here 02:00:00 rather than 00:00:00):

DatetimeIndex(['2005-01-01 00:00:00', '2005-01-01 01:00:00',
           '2005-01-01 02:00:00', '2005-01-01 03:00:00',
           '2005-01-01 04:00:00', '2005-01-01 05:00:00',
           '2005-01-01 06:00:00', '2005-01-01 07:00:00',
           '2005-01-01 08:00:00', '2005-01-01 09:00:00',
           ...
           '2005-04-30 15:00:00', '2005-04-30 16:00:00',
           '2005-04-30 17:00:00', '2005-04-30 18:00:00',
           '2005-04-30 19:00:00', '2005-04-30 20:00:00',
           '2005-04-30 21:00:00', '2005-04-30 22:00:00',
           '2005-04-30 23:00:00', '2005-05-01 00:00:00'],
          dtype='datetime64[ns]', length=2881, freq='H')

Advertisement

Answer

You could try something like this:

import pandas as pd

start_date = '2005-1-1 02:00:00'
end_date   = '2005-5-1 02:00:00'

date_range = pd.date_range(start=start_date, end=end_date, freq='H')
print(date_range)

Output:

DatetimeIndex(['2005-01-01 02:00:00', '2005-01-01 03:00:00',
               '2005-01-01 04:00:00', '2005-01-01 05:00:00',
               '2005-01-01 06:00:00', '2005-01-01 07:00:00',
               '2005-01-01 08:00:00', '2005-01-01 09:00:00',
               '2005-01-01 10:00:00', '2005-01-01 11:00:00',
               ...
               '2005-04-30 17:00:00', '2005-04-30 18:00:00',
               '2005-04-30 19:00:00', '2005-04-30 20:00:00',
               '2005-04-30 21:00:00', '2005-04-30 22:00:00',
               '2005-04-30 23:00:00', '2005-05-01 00:00:00',
               '2005-05-01 01:00:00', '2005-05-01 02:00:00'],
              dtype='datetime64[ns]', length=2881, freq='H')
   
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement