Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create dataframe with datetime hourly frequency

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
like image 581
user10317766 Avatar asked Oct 26 '25 01:10

user10317766


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]
like image 159
ALollz Avatar answered Oct 28 '25 14:10

ALollz


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)
like image 39
vielkind Avatar answered Oct 28 '25 14:10

vielkind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!