Random Date Generator

  • Share this:

Code introduction


This function generates a random date within a specified range of years.


Technology Stack : Python built-in library datetime

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
import datetime

def generate_random_date(year_start=1970, year_end=2023):
    """
    Generates a random datetime object within a specified range.
    """
    year = random.randint(year_start, year_end)
    month = random.randint(1, 12)
    day = random.randint(1, 28)  # Assuming a non-leap year for simplicity
    return datetime.datetime(year, month, day)