Python datetime date range

Python Create List Of Dates Within Range

This step-by-step guide lets you know how to create a list of dates within a range of dates in Python. For example, you may want to create a list of dates from 1st January 2022 to 30th June 2022. Or you may want to generate a list of dates from today to the next/previous 30 days.

Goals of this lesson:

  • Generate a list of dates between two dates.
  • Iterate through a range of dates.
  • Generate a list of dates between two dates using pandas.
  • Generate a list of dates so that the difference between each date is 1 month.

Table of contents

How to create a list of dates within a date range in Python

Use the below steps to create a list of dates between two dates in Python using the date and timedelta classes from the datetime module.

  1. Import the date and timedelta class from a datetime module Use the date class to create dates and the timedelta class to specify the frequency. Frequency means the difference between the current and next date in the result list.
  2. Define the start date and end date Set the start date and end date using the date class. Dates will get generated between these two dates.
  3. Specify the frequency using timedelta Use the timedelta class to specify the increment value. This can be anything like 1 second, 1 hour, or 1 day.

Example: create a list of dates within a range of dates

In this example, we specify two dates and create a list with all the dates in between them.

from datetime import date, timedelta start_dt = date(2022, 6, 10) end_dt = date(2022, 6, 15) # difference between current and previous date delta = timedelta(days=1) # store the dates between two dates in a list dates = [] while start_dt 
Dates between 2022-06-16 and 2022-06-15 [datetime.date(2022, 6, 10), datetime.date(2022, 6, 11), datetime.date(2022, 6, 12), datetime.date(2022, 6, 13), datetime.date(2022, 6, 14), datetime.date(2022, 6, 15)]

Example 2: Create a list of the next 7 dates starting from the current date

Here we’ll use list comprehension to get the desired result.

import datetime num_of_dates = 3 start = datetime.datetime.today() date_list = [start.date() + datetime.timedelta(days=x) for x in range(num_of_dates)] print('Next 3 days starting from today') print(date_list)
Next 3 days starting from today [datetime.date(2023, 2, 16), datetime.date(2023, 2, 17), datetime.date(2023, 2, 18)]

Example 3: Create a list of the previous 7 dates starting from the current date

import datetime num_of_dates = 3 start = datetime.datetime.today() date_list = [start.date() - datetime.timedelta(days=x) for x in range(num_of_dates)] print('Previous 3 days starting from today') print(date_list)
Previous 3 days starting from today [datetime.date(2023, 2, 16), datetime.date(2023, 2, 15), datetime.date(2023, 2, 14)]

Generate a date range using pandas

We can also use the pandas date_range() to create a list of dates within a date range.

We need to pass the following parameters to the date_range() function.

  • start : str or datetime object. The Start date (Left bound for generating dates).
  • end : str or datetime object. The end date (Right bound for generating dates).
  • periods : Number of periods to generate.
  • freq : default ‘D’, which is a calendar day. i.e., Each next date in the list is generated by adding one day to a preceding date. Read this for a list of all frequency aliases.

Of the four parameters, the start, end, periods, and freq, exactly three must be specified.

Example 1: Create a date range by specifying the start and end date with the default daily frequency.

 from datetime import datetime import pandas as pd # start date start_date = datetime.strptime("2022-10-17", "%Y-%m-%d") end_date = datetime.strptime("2022-10-23", "%Y-%m-%d") # difference between each date. D means one day D = 'D' date_list = pd.date_range(start_date, end_date, freq=D) print(f"Creating list of dates starting from to ") print(date_list) # if you want dates in string format then convert it into string print(date_list.strftime("%Y-%m-%d"))
Creating list of dates starting from 2022-10-17 00:00:00 to 2022-10-23 00:00:00 DatetimeIndex(['2022-10-17', '2022-10-18', '2022-10-19', '2022-10-20', '2022-10-21', '2022-10-22', '2022-10-23'], dtype='datetime64[ns]', freq='D') Index(['2022-10-17', '2022-10-18', '2022-10-19', '2022-10-20', '2022-10-21', '2022-10-22', '2022-10-23'], dtype='object')

Example 2: create a date range by specifying the start date and number of dates you want

from datetime import datetime import pandas as pd start_date = datetime.strptime("2022-10-20", "%Y-%m-%d") # periods means how many dates you want date_list = pd.date_range(start_date, periods=5, freq='D') print(f"Creating list of 5 dates starting from ") print(date_list)
Creating list of, 5 dates starting from 2022-10-20 00:00:00 DatetimeIndex(['2022-10-20', '2022-10-21', '2022-10-22', '2022-10-23', '2022-10-24'], dtype='datetime64[ns]', freq='D')

Example 3: Createa monthly date range

Let’s see how to create a date range on specific dates for each month. We need to change the freq (frequency) to ‘M’ (month-end frequency).

from datetime import datetime import pandas as pd start_date = datetime.strptime("2022-10-20", "%Y-%m-%d") date_list = pd.date_range(start_date, periods=5, freq='M') print(f"Creating list of 5 dates starting from with difference in each date is 1 month") print(date_list) # frequency of 6 months print(f"Creating list of 5 dates starting from with difference in each date is 6 month") date_list = pd.date_range(start_date, periods=5, freq='6M') print(date_list)
Creating list of 5 dates starting from 2022-10-20 00:00:00 with difference in each date is 1 month DatetimeIndex(['2022-10-31', '2022-11-30', '2022-12-31', '2023-01-31', '2023-02-28'], dtype='datetime64[ns]', freq='M') Creating list of 5 dates starting from 2022-10-20 00:00:00 with difference in each date is 6 month DatetimeIndex(['2022-10-31', '2023-04-30', '2023-10-31', '2024-04-30', '2024-10-31'], dtype='datetime64[ns]', freq='6M')

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Creating a range of dates in Python using datetime

Datetime Creating A Range Of Dates In Python

In this tutorial, we will take a look at the datetime module in python enables date and time manipulation for various programs. The datetime module contains a variety of function that allows parsing and formatting of dates and time formats. To create dates, we import the datetime module and use the datetime() constructor.

The datetime class can also take up other arguments for different time and time zones like hour, minutes or seconds. These arguments are optional which has default value of 0 for the time zone parameter(0 means None).

Implementing datetime in Python

To use this module for manipulating date and time in python, we need to install the datetime module in our system. Run the following code in your command prompt in administrator mode.

We can create a single datetime object in the following manner:

import datetime DATE = datetime.datetime(2023, 2, 13) print(DATE)

The output would be:

Using for loop to display a range of dates

This example uses the datetime module and defines a simple function to display a range of dates between two given dates.

#importing required modules from datetime import timedelta from datetime import date #function for creating a range of dates def rangeofdates(startdate, enddate): for n in range(int ((enddate - startdate).days)+1): yield startdate + timedelta(n) #defining beginning and end dates startdate = date(2023, 2, 13) enddate = date(2023, 2, 24) #displaying the dates using the functions for dt in rangeofdates(startdate, enddate): print(dt.strftime("%Y-%m-%d"))

The output will be something as shown below:

2023-02-13 2023-02-14 2023-02-15 2023-02-16 2023-02-17 2023-02-18 2023-02-19 2023-02-20 2023-02-21 2023-02-22 2023-02-23 2023-02-24

For Loop Utilization For Range Of Dates

Using Lists to create a comprehensive range of dates

We can use the append() function to create a list of dates in a range.

#importing datetime import datetime #setting startdate startdate = datetime.date(2023,2,13) #setting a counter Count = 5 #range of dates as a list datelist = [] #creating the dates list for day in range(Count): date = (startdate + datetime.timedelta(days = day)).isoformat() datelist.append(date) # printing result print("Next 5 dates list: " + str(datelist))

The output of the above code will be:

Next 5 dates list: ['2023-02-13', '2023-02-14', '2023-02-15', '2023-02-16', '2023-02-17']

List Of Dates

Using pandas to create a range of dates

We can also use the pandas package along with datetime to create a range of dates. To know more about pandas, visit the official documentation.

#importing datetime import datetime #importing pandas import pandas as pd # initializing the start date startdate = datetime.datetime.strptime("13-2-2023", "%d-%m-%Y") # initializing the counter for dates count= 10 #generating the dates date_generated = pd.date_range(startdate, periods=10) #displaying the generated dates print(date_generated.strftime("%d-%m-%Y"))
Index(['13-02-2023', '14-02-2023', '15-02-2023', '16-02-2023', '17-02-2023', '18-02-2023', '19-02-2023', '20-02-2023', '21-02-2023', '22-02-2023'], dtype='object')

Using Pandas For A Range Of Dates

Customize the start and end dates for a range of dates

We need to develop a program which would allow user input for customizing our program. Let’s see how we can accommodate user input to create a range of dates.

#importing required modules from datetime import timedelta import datetime #taking user input for start date styear = int(input('Enter start year=')) stmonth = int(input('Enter start month=')) stday = int(input('Enter start day=')) datestart = datetime.date(styear, stmonth, stday) #taking user input for end date endyear = int(input('Enter last year=')) endmonth = int(input('Enter last month=')) endday = int(input('Enter last day=')) dateend = datetime.date(endyear, endmonth, endday) #function for creating a range of dates def rangeofdates(startdate, enddate): for n in range(int ((enddate - startdate).days)+1): yield startdate + timedelta(n) #displaying the dates using the functions for dt in rangeofdates(datestart, dateend): print(dt.strftime("%Y-%m-%d"))

The output of the above code would be:

Enter start year=2023 Enter start month=2 Enter start day=13 Enter last year=2023 Enter last month=2 Enter last day=28 2023-02-13 2023-02-14 2023-02-15 2023-02-16 2023-02-17 2023-02-18 2023-02-19 2023-02-20 2023-02-21 2023-02-22 2023-02-23 2023-02-24 2023-02-25 2023-02-26 2023-02-27 2023-02-28

Customize And Take User Input

Summary.

This article demonstrates the various ways in which you can create a range of dates between two given dates defined by the user using the datetime() module in python. This is very useful tool in python programming and can be used to optimize or change timestamps accordingly. To know more about the datetime() constructor, visit the official page.

Источник

Читайте также:  Список описаний
Оцените статью