ItSolutionStuff.com

Python List All Dates Between Two Dates Example

By Hardik Savani • October 30, 2023
Python

In this article we will cover on how to implement python get dates between two dates. In this article, we will implement a python get all dates between two dates. I would like to show you how to get all dates between two dates in python. We will look at example of python list all dates between two dates. Follow bellow tutorial step of python get all dates between two datetime.

In this example, I will give two examples one example will get all dates between two dates using datetime and timedelta, and the second example find all dates between two dates using pandas. so let's see both examples and use them for you.

You can use these examples with python3 (Python 3) version.

Example 1:

main.py

from datetime import datetime, timedelta
  
# Create Custom Function
def date_range(start, end):
    delta = end - start
    days = [start + timedelta(days=i) for i in range(delta.days + 1)]
    return days
  
startDate = datetime(2022, 6, 1)
endDate = datetime(2022, 6, 10)
      
datesRange = date_range(startDate, endDate);
print(datesRange)

Output:

[
    datetime.datetime(2022, 6, 1, 0, 0), 
    datetime.datetime(2022, 6, 2, 0, 0), 
    datetime.datetime(2022, 6, 3, 0, 0), 
    datetime.datetime(2022, 6, 4, 0, 0), 
    datetime.datetime(2022, 6, 5, 0, 0), 
    datetime.datetime(2022, 6, 6, 0, 0), 
    datetime.datetime(2022, 6, 7, 0, 0), 
    datetime.datetime(2022, 6, 8, 0, 0), 
    datetime.datetime(2022, 6, 9, 0, 0), 
    datetime.datetime(2022, 6, 10, 0, 0)
]

Example 2:

main.py

import pandas
from datetime import datetime, timedelta
  
startDate = datetime(2022, 6, 1)
endDate = datetime(2022, 6, 10)
  
# Getting List of Days using pandas
datesRange = pandas.date_range(startDate,endDate-timedelta(days=1),freq='d')
print(datesRange);

Output:

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

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Check if Today is Sunday or not in Python?

Read Now →

How to Check if Today is Tuesday or not in Python?

Read Now →

Python Subtract Seconds from DateTime Example

Read Now →

How to Add Minutes to DateTime in Python?

Read Now →

Python DELETE Request Example Tutorial

Read Now →

Python POST Request with Parameters Example

Read Now →

Python Subtract Hours from Datetime Example

Read Now →

How to Subtract Year to Date in Python?

Read Now →

How to Subtract Months to Date in Python?

Read Now →

How to Subtract Days from Date in Python?

Read Now →

How to Get Current Month in Python?

Read Now →