Random Date Generator within a Range

  • Share this:

Code introduction


This function takes two parameters, the start date and end date of the date range, and then generates a random date within this range.


Technology Stack : datetime, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import datetime
import random

def generate_random_date(start_date, end_date):
    """
    生成一个指定日期范围内的随机日期。

    参数:
    start_date (str): 日期范围的起始日期,格式为YYYY-MM-DD。
    end_date (str): 日期范围的结束日期,格式为YYYY-MM-DD。

    返回:
    str: 随机生成的日期,格式为YYYY-MM-DD。
    """
    start = datetime.datetime.strptime(start_date, '%Y-%m-%d')
    end = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    delta = end - start
    random_number_of_days = random.randrange(delta.days)
    random_date = start + datetime.timedelta(days=random_number_of_days)
    return random_date.strftime('%Y-%m-%d')