Random Datetime Generator

  • Share this:

Code introduction


This function generates a random datetime between a specified start date and end date, with an option to specify the datetime format.


Technology Stack : datetime, timedelta, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from datetime import datetime
import numpy as np

def random_datetime_format(start_date, end_date, format="%Y-%m-%d %H:%M:%S"):
    """
    Generate a random datetime between start_date and end_date with a specified format.
    """
    time_between_dates = end_date - start_date
    random_number_of_seconds = random.randrange(time_between_dates.total_seconds())
    random_date = start_date + timedelta(seconds=random_number_of_seconds)
    return random_date.strftime(format)

# JSON Explanation