Random Date Formatting Between Two Dates

  • Share this:

Code introduction


This function takes two dates (year, month, day) as input, generates a random date and time between these two dates, and returns this date and time in a random format.


Technology Stack : Delorean

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from delorean import Delorean

def random_date_time_formatting(start_date, end_date):
    """
    This function takes a start and end date and randomly formats the date and time
    between these two dates.
    """
    start = Delorean(years=start_date.year, months=start_date.month, days=start_date.day)
    end = Delorean(years=end_date.year, months=end_date.month, days=end_date.day)
    
    random_date = start.add(random.randint(0, (end - start).days)).datetime()
    random_date_str = random.choice(['%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H:%M', '%d-%m-%Y %H:%M:%S', '%m/%d/%Y'])
    
    return random_date.strftime(random_date_str)                
              
Tags: