Random Date String Generator with Format

  • Share this:

Code introduction


The function generates a random date string with a specified format. It first defines a time range, then randomly selects a date within this range, and finally formats the date into a string using the Babel library's format_date function.


Technology Stack : Python, Babel

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def generate_random_date_string(date_format):
    from random import randint
    from datetime import datetime, timedelta
    from babel.dates import format_date

    # Define the range for the random date
    start_date = datetime.now() - timedelta(days=365)
    end_date = datetime.now()
    random_date = start_date + timedelta(days=randint(0, 365))

    # Generate a random date string
    formatted_date = format_date(random_date, format=date_format, locale='en_US')
    return formatted_date                
              
Tags: