create dataframe with datetime hourly frequency

Viewed 5068

I need to create a pandas dataframe with first column as date + time and with hourly frequency.

So in the dataframe, it will be complete year date with hourly time i.e 365 * 24 = 8760 rows in the first column.

sample data output:

Hours
2018-01-01 00:00:00
2018-01-01 01:00:00
2018-01-01 02:00:00
...
...
...
2018-01-01 23:00:00
2 Answers

Use pd.date_range

import pandas as pd

df = pd.DataFrame(
        {'Hours': pd.date_range('2018-01-01', '2019-01-01', freq='1H', closed='left')}
     )

Output:

                   Hours
0    2018-01-01 00:00:00
1    2018-01-01 01:00:00
2    2018-01-01 02:00:00
3    2018-01-01 03:00:00
...                  ...
8759 2018-12-31 23:00:00

[8760 rows x 1 columns]

You can use pandas.DatetimeIndex.

import pandas as pd

idx = pd.DatetimeIndex(freq="h", start="2018-01-01", periods=365*24)

Then you can use that index when you create your dataframe:

df = pd.DataFrame(index=idx)
Related