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.

pip install datetime

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:

2023-02-13 00:00:00

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
For Loop Utilization For Range Of Dates

Also read: Converting Alphabet Letters to Numbers Using Python.

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

The output will be:

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
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
Customize And Take User Input

Also read: Python Course for Beginners Online FREE

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.