Random Datetime Generator

  • Share this:

Code introduction


This function generates a random datetime string in the specified format. It first gets the current time, then calculates the number of seconds since the start of the day, and finally adds these seconds to the current time and returns it in the specified format.


Technology Stack : Behave, datetime, random

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
from behave import given, when, then
from random import choice
import datetime

def generate_random_datetime(format="%Y-%m-%d %H:%M:%S"):
    """
    Generate a random datetime string in the given format.
    """
    now = datetime.datetime.now()
    random_seconds = now.timestamp() - now.replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
    random_datetime = now + datetime.timedelta(seconds=random_seconds)
    return random_datetime.strftime(format)