Random Datetime Generator

  • Share this:

Code introduction


This function generates a random datetime between the current time minus 'arg1' days and the current time plus 'arg2' days based on the input parameters.


Technology Stack : datetime, timedelta, random.randint

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from wheel import randomwheel
from datetime import datetime

def generate_random_datetime(arg1, arg2):
    """
    Generate a random datetime between the current time minus 'arg1' days and 'arg2' days from now.
    
    Parameters:
    arg1 (int): Number of days to subtract from the current time.
    arg2 (int): Number of days to add to the current time.
    
    Returns:
    datetime: A random datetime between the calculated range.
    """
    current_time = datetime.now()
    start_time = current_time - timedelta(days=arg1)
    end_time = current_time + timedelta(days=arg2)
    random_time = start_time + timedelta(seconds=random.randint(0, int((end_time - start_time).total_seconds())))
    return random_time