How to Generate a Random Date Between Two Dates in Python?

4.9/5 - (7 votes)

Problem Formulation and Solution Overview

This article will show you how to generate a random date between two dates in Python.


💬 Question: How would we write code to generate a random date between two dates?

We can accomplish this task by one of the following options:


Preparation

Examples 1-3 in this article require the datetime and random libraries to run error-free.

In this regard, add these lines to the top of these snippets.

import datetime
from datetime import timedelta
import random

Method 1: Use timedelta and random()

This example uses datetime.timedelta() and random.random() to generate an arbitrary date between two dates.

start_date = datetime.datetime.now()
end_date = start_date + timedelta(days=10)

random_date = start_date + (end_date - start_date) * random.random()
print(random_date)

The first line calls the datetime.datetime.now() function, which generates the current datetime. The results save to start_date.

2022-10-05 13:19:57.290079

The following line calculates the end_date by adding 10 days to the start_date (timedelta(days=10). The results save to end_date.

2022-10-15 13:27:18.943273

On the next line, the number of days between the start_date and end_date is calculated (end_date - start_date), resulting, in this case, to 10. A random number is generated by multiplying this value by random.random().

This number is added to the start_date (days), saved as random_date, and output to the terminal.

2022-10-13 22:12:43.285792
Create a List of Random Numbers — The Most Pythonic Way

Method 2: Use timedelta() and randint()

This example uses datetime.timedelta() and random.randint() to generate an arbitrary date between two dates.

start_date = datetime.date(2022, 10, 1)
end_date   = datetime.date(2022, 11, 30)

num_days   = (end_date - start_date).days
rand_days   = random.randint(1, num_days)
random_date = start_date + datetime.timedelta(days=rand_days)
print(random_date)

This code’s first two (2) lines declare two (2) dates by calling the datetime.date() function and passing in the requisite: year, month, and day arguments. These save to start_date and end_date, respectively.

2022-10-01
2022-11-30

The following line calculates the number of days between the start_date and end_date. The results save to num_days.

60

On the next line, the random.randint() function is called and passed two (2) arguments, a start position (1) and a stop position (num_days). This returns a random integer and saves it to rand_days.

8

Then, a random date is calculated by calling passing the above generated random number (rand_days) to datetime.timedelta() and adding said number to the start_date.

The results save to random_date and are output to the terminal. In this case, the random number 41 (days) was added to random_date.

2022-11-11
Working with date-time in Pandas

Method 3: Use combine() and random()

This example uses datetime.datetime.combine() and random.random() to generate an arbitrary date between two dates.

start_date = datetime.date(2022, 10, 1)
end_date = datetime.date(2022, 10, 10)

random_date = start + (end - start) * random.random()
random_date = datetime.datetime.combine(random_date, datetime.datetime.min.time())
print(random_date)

The code’s first two (2) lines declare two (2) dates by calling the datetime.date() function and passing in the requisite: year, month, and day arguments. These save to start_date and end_date, respectively.

2022-10-01
2022-10-10

Next, the number of days between the start_date and end_date is calculated, and a random number is generated from this.

3

The following line calls the datetime.datetime.combine() function and passes it two arguments, random_date, and datetime.datetime.min.time() to generate a random date and append a default time format to the output. The results save to random_date and output to the terminal.

2022-10-03 00:00:00

Method 4: Use date_range() and sample()

This example uses date_range() and sample() to generate five (5) arbitrary dates between two dates.

import pandas as pd 

def generate_dates(start, end, n, seed=1, replace=False):
    dates = pd.date_range(start, end).to_series()
    return dates.sample(n, replace=replace, random_state=seed)

print(generate_dates('20221001', '20221010', 5, seed=1))

The above code imports the pandas library, allowing access to and manipulating of the data.

The following lines declare a function generate_dates, and passes it the following:

  • start: a start date formatted as ‘20220101’.
  • end: an end date formatted as ‘20220331’
  • seed: the total number of dates to generate
  • replace=False: allow (True) or disallow (False) sampling of the same row more than once.

Inside this function, the start and end dates are determined and converted to a Series (to_series()). In, this case 10 dates are generated from the start_date to the end_date inclusive.

2022-10-01 2022-10-01
2022-10-02 2022-10-02
2022-10-03 2022-10-03
2022-10-04 2022-10-04
2022-10-05 2022-10-05
2022-10-06 2022-10-06
2022-10-07 2022-10-07
2022-10-08 2022-10-08
2022-10-09 2022-10-09
2022-10-10 2022-10-10

Five (5) random dates are retrieved from the above and returned when the function is called on the following line. The result is as follows.

2022-10-06 2022-10-06
2022-10-09 2022-10-09
2022-10-10 2022-10-10
2022-10-06 2022-10-06
2022-10-01 2022-10-01
10 Minutes to Pandas in 5 Minutes (Okay 8)

Summary

This article has provided four (4) ways to generate a random date between two dates to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programming Humor