PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Python Create List Of Dates Within Range

Python Create List Of Dates Within Range

Updated on: March 9, 2023 | Leave a Comment

    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
      • Example: create a list of dates within a range of dates
      • Example 2: Create a list of the next 7 dates starting from the current date
      • Example 3: Create a list of the previous 7 dates starting from the current date
    • Generate a date range using pandas
      • Example 1: Create a date range by specifying the start and end date with the default daily frequency.
      • Example 2: create a date range by specifying the start date and number of dates you want
      • Example 3: Createa monthly date range

    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.

      Let’s assume you want to generate a list of dates between 1st January 2022 and 30th June 2022, with an increment value of 1 day. In this case, the timedelta is timedelta(days=1). Each next date in the list is generated by adding one day to a preceding date.

    4. Iterating through a range of date

      Use the while loop to iterate between the start and end date till the start date is less than the end date.

      In each loop iteration, add the start date to a result list. Next, increment the start date by adding the timedelta. For example, if the timedelta is one day, the start date will be incremented by one day in each iteration.

    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 <= end_dt:
        # add current date to list by converting  it to iso format
        dates.append(start_dt.isoformat())
        # increment start date by timedelta
        start_dt += delta
    
    print('Dates between', start_dt, 'and', end_dt)
    print(dates)

    Output:

    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)

    Output:

    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)

    Output:

    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 {start_date} to {end_date}")
    print(date_list)
    
    # if you want dates in string format then convert it into string
    print(date_list.strftime("%Y-%m-%d"))

    Output:

    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 {start_date}")
    print(date_list)

    Output:

    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 {start_date} with difference in each date is 1 month")
    print(date_list)
    
    # frequency of 6 months
    print(f"Creating list of 5 dates starting from {start_date} with difference in each date is 6 month")
    date_list = pd.date_range(start_date, periods=5, freq='6M')
    print(date_list)

    Output:

    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')

    Filed Under: Pandas, Python, Python DateTime

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

    TweetF  sharein  shareP  Pin

    About Vishal

    Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

    Related Tutorial Topics:

    Pandas Python Python DateTime

    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
    Exercises
    Quizzes

    Leave a Reply Cancel reply

    your email address will NOT be published. all comments are moderated according to our comment policy.

    Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

    Posted In

    Pandas Python Python DateTime
    TweetF  sharein  shareP  Pin

      Python DateTime

    • Python DateTime Guide
    • Python Get Current DateTime
    • Python DateTime Formatting
    • Python String to DateTime
    • Python Timestamp
    • Python Timedelta
    • Python TimeZones
    • List All TimeZones in Python

    All Python Topics

    Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

    About PYnative

    PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

    Explore Python

    • Learn Python
    • Python Basics
    • Python Databases
    • Python Exercises
    • Python Quizzes
    • Online Python Code Editor
    • Python Tricks

    Follow Us

    To get New Python Tutorials, Exercises, and Quizzes

    • Twitter
    • Facebook
    • Sitemap

    Legal Stuff

    • About Us
    • Contact Us

    We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

    Copyright © 2018–2023 pynative.com