Python - Generate k random dates between two other dates
Last Updated :
21 Apr, 2023
Given two dates, the task is to write a Python program to get K dates randomly.
Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1), K = 7
Output : [datetime.date(2015, 6, 18), datetime.date(2015, 6, 25), datetime.date(2015, 6, 29), datetime.date(2015, 6, 11), datetime.date(2015, 6, 11), datetime.date(2015, 6, 10), datetime.date(2015, 6, 24)]
Explanation : 7 random dates starting from 3 June 2015 to 1 July 2015 are generated.
Input : test_date1, test_date2 = date(2015, 6, 3), date(2015, 8, 1), K = 6
Output : [datetime.date(2015, 6, 20), datetime.date(2015, 7, 22), datetime.date(2015, 6, 29), datetime.date(2015, 6, 18), datetime.date(2015, 6, 13), datetime.date(2015, 7, 14)]
Explanation : 6 random dates starting from 3 June 2015 to 1 August 2015 are generated.
Method #1 : Using choices() + loop + timedelta()
In this, we extract all dates in range using loop and timedelta() of 1-day difference. Among them K random dates are chosen using choices().
Python3
# Python3 code to demonstrate working of
# Random K dates in Range
# Using choices() + timedelta() + loop
from datetime import date, timedelta
from random import choices
# initializing dates ranges
test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1)
# printing dates
print("The original range : " + str(test_date1) + " " + str(test_date2))
# initializing K
K = 7
res_dates = [test_date1]
# loop to get each date till end date
while test_date1 != test_date2:
test_date1 += timedelta(days=1)
res_dates.append(test_date1)
# random K dates from pack
res = choices(res_dates, k=K)
# printing
print("K random dates in range : " + str(res))
Output:
The original range : 2015-06-03 2015-07-01
K random dates in range : [datetime.date(2015, 6, 25), datetime.date(2015, 6, 10), datetime.date(2015, 6, 18), datetime.date(2015, 6, 7), datetime.date(2015, 6, 4), datetime.date(2015, 6, 16), datetime.date(2015, 6, 12)]
Time complexity : O(n + klogn)
Space complexity : O(n + k)
Method #2 : Using randrange() + timedelta() + loop
In this, a total number of days between ranges is extracted and that range is used to get elements K times, adding a random index number from start date extracted using randrange().
Python3
# Python3 code to demonstrate working of
# Random K dates in Range
# Using randrange() + timedelta() + loop
from datetime import date, timedelta
import random
# initializing dates ranges
test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1)
# printing dates
print("The original range : " + str(test_date1) + " " + str(test_date2))
# initializing K
K = 7
# getting days between dates
dates_bet = test_date2 - test_date1
total_days = dates_bet.days
res = []
for idx in range(K):
random.seed(a=None)
# getting random days
randay = random.randrange(total_days)
# getting random dates
res.append(test_date1 + timedelta(days=randay))
# printing
print("K random dates in range : " + str(res))
Output:
The original range : 2015-06-03 2015-07-01
K random dates in range : [datetime.date(2015, 6, 26), datetime.date(2015, 6, 5), datetime.date(2015, 6, 6), datetime.date(2015, 6, 18), datetime.date(2015, 6, 21), datetime.date(2015, 6, 15), datetime.date(2015, 6, 12)]
Time complexity : O(k)
Space Complexity : O(k)
Method #3: Using numpy.random.choice() + timedelta()
step-by-step breakdown of the program:
- Import the required modules - datetime and numpy.
- Define the starting and ending dates of the date range, test_date1 and test_date2, respectively, using the date() function from the datetime module.
- Print the original date range using the print() function and string formatting.
- Initialize the value of K, the number of random dates to generate.
- Calculate the number of days between the two dates using the timedelta() function from the datetime module.
- Convert the total_days object to an integer value using the days attribute.
- Use the numpy.random.choice() function to generate an array of K unique random integers from 0 to total_days-1 without replacement.
- Iterate over the randays array and convert each element to an integer value using the int() function.
- Use the timedelta() function to calculate the date corresponding to each random day in the date range.
- Append each resulting date to a list called res.
- Print the list of K random dates using the print() function and string formatting.
Python3
from datetime import date, timedelta
import numpy as np
# initializing dates ranges
test_date1, test_date2 = date(2015, 6, 3), date(2015, 7, 1)
# printing dates
print("The original range : " + str(test_date1) + " " + str(test_date2))
# initializing K
K = 7
# getting days between dates
dates_bet = test_date2 - test_date1
total_days = dates_bet.days
# create an array of total days and select K random values without replacement
randays = np.random.choice(total_days, K, replace=False)
# getting random dates
res = [test_date1 + timedelta(days=int(day)) for day in randays]
# printing
print("K random dates in range : " + str(res))
OUTPUT :
The original range : 2015-06-03 2015-07-01
K random dates in range : [datetime.date(2015, 6, 7), datetime.date(2015, 6, 13), datetime.date(2015, 6, 25), datetime.date(2015, 6, 10), datetime.date(2015, 6, 8), datetime.date(2015, 6, 22), datetime.date(2015, 6, 28)]
Time complexity: O(K)
Auxiliary space: O(K)
Similar Reads
Python program to find number of days between two given dates
Given two dates, Write a Python program to find the total number of days between them. Examples: Input : dt1 = 13/12/2018, dt2 = 25/2/2019Output : 74 daysInput : dt1 = 01/01/2004, dt2 = 01/01/2005Output : 366 days Naive Approach: One Naive Solution is to start from dt1 and keep counting the days til
5 min read
Generate a List of Random Numbers Without Duplicates in Python
There are a few ways to generate a list of random numbers without duplicates in Python. Letâs look at how we can generate a list of random numbers without any duplicates.Using random.sample()This random.sample() method allows us to generate a list of unique random numbers in a single step. Pythonimp
2 min read
Python Program to Get total Business days between two dates
Given two dates, our task is to write a Python program to get total business days, i.e weekdays between the two dates. Example: Input : test_date1, test_date2 = datetime(2015, 6, 3), datetime(2015, 7, 1) Output : 20 Explanation : Total weekdays, i.e business days are 20 in span. Input : test_date1,
6 min read
Python - Random insertion of elements K times
Given 2 list, insert random elements from List 2 to List 1, K times at random position. Input : test_list = [5, 7, 4, 2, 8, 1], add_list = ["Gfg", "Best", "CS"], K = 2 Output : [5, 7, 4, 2, 8, 1, 'Best', 'Gfg'] Explanation : Random elements from List 2 are added 2 times. Input : test_list = [5, 7, 4
5 min read
Python Generate Random Float Number
Generating a random float number in Python means producing a decimal number that falls within a certain range, often between 0.0 and 1.0. Python provides multiple methods to generate random floats efficiently. Letâs explore some of the most effective ones.Using random.random()random.random() method
2 min read
Generate Random String Without Duplicates in Python
When we need to create a random string in Python, sometimes we want to make sure that the string does not have any duplicate characters. For example, if we're generating a random password or a unique identifier, we might want to ensure each character appears only once. Using random.sample()Using ran
2 min read
Python Program to check date in date range
Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range. Example: Input : test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)]
10 min read
Python - Generate Random String of given Length
Generating random strings is a common requirement for tasks like creating unique identifiers, random passwords, or testing data. Python provides several efficient ways to generate random strings of a specified length. Below, weâll explore these methods, starting from the most efficient.Using random.
2 min read
Python program to randomly create N Lists of K size
Given a List, the task is to write a Python program to randomly generate N lists of size K. Examples: Input : test_list = [6, 9, 1, 8, 4, 7], K, N = 3, 4 Output : [[8, 7, 6], [8, 6, 9], [8, 1, 6], [7, 8, 9]] Explanation : 4 rows of 3 length are randomly extracted. Input : test_list = [6, 9, 1, 8, 4,
5 min read
Generating random number list in Python
In Python, we often need to generate a list of random numbers for tasks such as simulations, testing etc. Pythonâs random module provides multiple ways to generate random numbers. For example, we might want to create a list of 5 random numbers ranging from 1 to 100. This article explores different m
3 min read