Random Timezone DateTime Generator

  • Share this:

Code introduction


This function takes a date string and a timezone name, randomly selects a timezone, and returns a DateTime object with the specified timezone.


Technology Stack : Pendulum

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from pendulum import DateTime, timezone

def random_timezone_datetime(date, timezone_name):
    """
    Generate a random datetime with a specific timezone.

    Args:
    date (str): The date string in ISO 8601 format.
    timezone_name (str): The name of the timezone.

    Returns:
    pendulum.DateTime: A random datetime object with the specified timezone.
    """
    # Randomly select a timezone from a list of available timezones
    timezones = timezone.all_timezones
    random_timezone = random.choice(timezones)

    # Create a datetime object with the specified date and random timezone
    random_datetime = DateTime(date).in_timezone(random_timezone)
    
    return random_datetime                
              
Tags: