[파이썬] 날짜와 시간의 날짜 범위 순회

Python provides various ways to handle dates and times, making it convenient to work with date ranges. In this blog post, we will explore how to iterate over date ranges using the datetime module in Python.

Getting Started

Before we start, let’s make sure the datetime module is imported:

import datetime

Iterating over Date Ranges

To iterate over a range of dates, we’ll use the date class from the datetime module. Here’s an example that demonstrates how to iterate over a range of dates:

start_date = datetime.date(2022, 1, 1)
end_date = datetime.date(2022, 1, 7)

current_date = start_date
while current_date <= end_date:
    print(current_date)
    current_date += datetime.timedelta(days=1)

In the code above, we define a start date (2022-01-01) and an end date (2022-01-07). We then initialize a variable current_date with the start date.

We use a while loop to iterate over the date range and print each date. The loop continues as long as the current_date is less than or equal to the end date. After each iteration, we use the timedelta function to add one day to the current_date.

The output of the above code will be:

2022-01-01
2022-01-02
2022-01-03
2022-01-04
2022-01-05
2022-01-06
2022-01-07

Customizing the Date Range

We can easily customize the date range by modifying the start and end dates in the code. For example:

start_date = datetime.date(2022, 3, 15)
end_date = datetime.date(2022, 3, 20)

By changing the start and end dates, we can iterate over different date ranges.

Handling Time as well

If we need to include time in our date range, we can use the datetime class instead of the date class. The principles remain the same, with the added flexibility of including time components.

Here’s an example that demonstrates how to iterate over a range of dates and times:

start_datetime = datetime.datetime(2022, 4, 1, 9, 0, 0)
end_datetime = datetime.datetime(2022, 4, 1, 17, 0, 0)

current_datetime = start_datetime
while current_datetime <= end_datetime:
    print(current_datetime)
    current_datetime += datetime.timedelta(hours=1)

In this code, we use the datetime class to define the start and end date-time values. We iterate over the date-time range, incrementing the current_datetime by one hour in each iteration.

Conclusion

In this blog post, we explored how to iterate over date ranges in Python using the datetime module. We learned how to define the start and end dates, iterate over the dates, and even include time components in the range.

Python’s datetime module provides powerful tools to handle dates and times, allowing us to efficiently work with various date ranges in our programs.