Random Datetime Generator between Two Dates

  • Share this:

Code introduction


This code defines a function that takes two datetime objects from the Arrow library as input and returns a random datetime between them. It uses the Pandas library to generate a random number of seconds.


Technology Stack : The code uses the Arrow library for datetime operations and the Pandas library for generating random numbers.

Code Type : Function

Code Difficulty : Advanced


                
                    
import random
import arrow
import pandas as pd

def random_datetime(arg1, arg2):
    """
    Generate a random datetime between two dates using Arrow and Pandas.
    
    Args:
    arg1 (arrow.Arrow): The start date.
    arg2 (arrow.Arrow): The end date.
    
    Returns:
    arrow.Arrow: A random datetime between the start and end dates.
    """
    start = arrow.get(arg1)
    end = arrow.get(arg2)
    random_seconds = random.randint(0, (end - start).seconds)
    random_datetime = start.shift(seconds=random_seconds)
    return random_datetime