How to Create a List of Dates in Python?

Estimated read time 2 min read

To create a list of dates in Python, you can use the datetime module. Here’s an example code that creates a list of dates for the first ten days of April 2022:

import datetime

# define the start date
start_date = datetime.date(2022, 4, 1)

# create a list of dates for the first ten days of April 2022
date_list = [start_date + datetime.timedelta(days=x) for x in range(10)]

# print the list of dates
print(date_list)

In this example, we first import the datetime module. Then we define the start date as a datetime.date object, using the datetime.date() function with year, month, and day as arguments.

Next, we use a list comprehension to create a new list date_list that contains ten dates starting from the start_date. We use the datetime.timedelta() function to add a specified number of days to the start_date. Finally, we print the list of dates using the print() function.

Note that you can modify the start_date and the range() function to generate a list of dates for any time period. You can also use other methods of the datetime module to manipulate the dates, such as adding months or years using the datetime.timedelta() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply