You can download this code by clicking the button below.
This code is now available for download.
The code defines a function that generates a random date between two given dates. It first converts the input date strings into datetime objects, then calculates the time difference between the two dates, randomly selects a second within this time difference, and finally adds this second to the start date to get a random date.
Technology Stack : Python, datetime, random
Code Type : The type of code
Code Difficulty : Intermediate
import random
import datetime
import fire
def generate_random_date(start_date, end_date):
"""
Generate a random date between the given start_date and end_date.
"""
start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
delta = end - start
random_seconds = random.randrange(delta.total_seconds())
return start + datetime.timedelta(seconds=random_seconds)
def main():
print(generate_random_date("2021-01-01", "2021-12-31"))
if __name__ == "__main__":
fire.Fire(main)