List All Dates Between Two Dates in Python Example
Hi Dev,
In this tutorial, you will learn list all dates between two dates in python example. I would like to share with you how to get date range between two dates in python. I would like to show you python get all dates between two dates. We will use python list all dates between two dates.
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.
so let's see following examples with output:
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')
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?