Random Date Generator Between Two Dates

  • Share this:

Code introduction


This function takes two date strings as arguments and generates a random date between these two dates.


Technology Stack : The packages and technologies used in the code include datetime and random.

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def generate_random_date(start_date, end_date):
    from datetime import datetime, timedelta
    import random
    
    start = datetime.strptime(start_date, '%Y-%m-%d')
    end = datetime.strptime(end_date, '%Y-%m-%d')
    delta = end - start
    
    random_days = random.randrange(delta.days)
    random_date = start + timedelta(days=random_days)
    
    return random_date.strftime('%Y-%m-%d')