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
from datetime import date, timedelta
from random import choices
test_date1, test_date2 = date( 2015 , 6 , 3 ), date( 2015 , 7 , 1 )
print ( "The original range : " + str (test_date1) + " " + str (test_date2))
K = 7
res_dates = [test_date1]
while test_date1 ! = test_date2:
test_date1 + = timedelta(days = 1 )
res_dates.append(test_date1)
res = choices(res_dates, k = K)
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
from datetime import date, timedelta
import random
test_date1, test_date2 = date( 2015 , 6 , 3 ), date( 2015 , 7 , 1 )
print ( "The original range : " + str (test_date1) + " " + str (test_date2))
K = 7
dates_bet = test_date2 - test_date1
total_days = dates_bet.days
res = []
for idx in range (K):
random.seed(a = None )
randay = random.randrange(total_days)
res.append(test_date1 + timedelta(days = randay))
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
test_date1, test_date2 = date( 2015 , 6 , 3 ), date( 2015 , 7 , 1 )
print ( "The original range : " + str (test_date1) + " " + str (test_date2))
K = 7
dates_bet = test_date2 - test_date1
total_days = dates_bet.days
randays = np.random.choice(total_days, K, replace = False )
res = [test_date1 + timedelta(days = int (day)) for day in randays]
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
How to generate a random letter in Python?
In this article, let's discuss how to generate a random letter. Python provides rich module support and some of these modules can help us to generate random numbers and letters. There are multiple ways we can do that using various Python modules. Generate a random letter using a string and a random
1 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. [GFGTABS
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 - Generate random number except K in list
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be per
3 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 random numbers plays an important role in programming. It can be used in data analysis, cryptography, or even in simulating games like dice rolls, choosing lottery numbers, or creating unpredictable patterns. When we talk about "float" numbers, we mean numbers with decimals (like 3.14 or
3 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