Python - pandas Automatic Date Generation with date_range
This article explains the date_range() function within the pandas library that can automatically generate dates.
Instead of manually entering dates in the index of data, it is convenient to use pandas’ date_range() when there are many values.
date_range() can be used as follows:
>>> pd.date_range(start='date', end='date', freq='frequency')
Let’s take a look at the following example.
>>> pd.date_range(start='2024/01/01', end='2024/01/07')
DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04',
'2024-01-05', '2024-01-06', '2024-01-07'],
dtype='datetime64[ns]', freq='D')
As seen in the output, you can confirm that it has output from the start date ‘2024/01/01’ to the end date ‘2024/01/07’.
Let’s look at another example.
>>> pd.date_range(start='2024-01-01 08:00', periods = 4, freq = 'H')
DatetimeIndex(['2024-01-01 08:00:00', '2024-01-01 09:00:00',
'2024-01-01 10:00:00', '2024-01-01 11:00:00'],
dtype='datetime64[ns]', freq='H')
From the result, you can see that starting from 08:00 on ‘2024-01-01’, four results are produced based on the frequency ‘H’ (hourly).
When setting the freq (frequency), various outputs are possible by referring to the Offset aliases in the link below.
Reference: https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases