[파이썬] pandas 날짜 및 시간의 범위 생성 (date_range)

Pandas is a popular data manipulation library in Python. One of its useful functions is date_range(), which allows you to generate a range of dates or times.

Generating a Date Range

To generate a date range using date_range(), you need to specify the start and end dates, and the frequency of the range. Here’s an example:

import pandas as pd

# Generate a daily date range from "2021-01-01" to "2021-01-10"
date_range = pd.date_range(start="2021-01-01", end="2021-01-10", freq="D")

print(date_range)

The code above will generate a date range starting from “2021-01-01” to “2021-01-10” with a frequency of daily. The freq parameter can take various values like “D” for daily, “M” for monthly, “W” for weekly, etc.

Output:

DatetimeIndex(['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04',
               '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08',
               '2021-01-09', '2021-01-10'],
              dtype='datetime64[ns]', freq='D')

As you can see, the date_range() function returns a DatetimeIndex object containing the generated dates.

Summary

Generating a date range using date_range() in pandas is a simple and powerful way to create a sequence of dates or times. By specifying the start and end dates, along with the frequency, you can easily generate the desired date range for your analysis or data manipulation tasks.