In this article, we will see how to generate a random date between two dates in Python.

There might be N no of scenarios where you may need to generate a random date between two dates in python. For example, simulation, data analysis, testing etc.

In python, by using the random & datetime module we can generate a random date between two other dates.

Here’s an example of how you can generate a random date between two other dates:

import random
import datetime

def random_date(start, end):
  return start + datetime.timedelta(
      seconds=random.randint(0, int((end - start).total_seconds())))

start = datetime.datetime(2020, 1, 1)
end = datetime.datetime(2021, 1, 1)
random_date = random_date(start, end)
print(random_date)

The random_date function in the above code accepts two datetime objects as arguments: start and end.

  • This function uses the datetime module’s timedelta class to calculate the number of seconds between two dates, and then generates a random integer between 0 and that number.
  • The programme generates a random date between start and end by adding the random number of seconds to the start date.
  • Please note that the random.randint function generates a random integer between the two arguments. In this case, the arguments are 0 and the number of seconds between the start and end dates.
  • By using int((end - start).total_seconds()), we ensure that the random integer will always be less than the number of seconds between the two dates.
  • Here, we set start to January 1st, 2020, and end to January 1st, 2021. The random_date function is then called, and the resulting random date is calculated & printed.

I hope this article is helpful for you to generate a random date between two other dates.

Categorized in:

Tagged in: