Open In App
Related Articles

Python – Generate k random dates between two other dates

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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:

  1. Import the required modules – datetime and numpy.
  2. Define the starting and ending dates of the date range, test_date1 and test_date2, respectively, using the date() function from the datetime module.
  3. Print the original date range using the print() function and string formatting.
  4. Initialize the value of K, the number of random dates to generate.
  5. Calculate the number of days between the two dates using the timedelta() function from the datetime module.
  6. Convert the total_days object to an integer value using the days attribute.
  7. Use the numpy.random.choice() function to generate an array of K unique random integers from 0 to total_days-1 without replacement.
  8. Iterate over the randays array and convert each element to an integer value using the int() function.
  9. Use the timedelta() function to calculate the date corresponding to each random day in the date range.
  10. Append each resulting date to a list called res.
  11. 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)



Last Updated : 21 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads