Randomize Time Components Based on Time Zone

  • Share this:

Code introduction


This function takes a date and a time zone as input, then randomly selects a time component (hour, minute, second, or microsecond) to add or subtract a random number of units, and returns the modified date and time.


Technology Stack : Pendulum library for date and time manipulation, random library for random selection.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def randomize_pendulum_features(date, time_zone):
    from pendulum import timezone, now
    from random import choice

    # Create a timezone object from the provided time zone
    tz = timezone(time_zone)

    # Get the current date and time in the provided time zone
    current_datetime = now(tz=tz)

    # Randomly select a time component to modify
    time_component = choice(['hour', 'minute', 'second', 'microsecond'])

    # Randomly decide to add or subtract a random number of units from the selected time component
    direction = choice(['add', 'subtract'])
    amount = choice(range(1, 10))

    # Modify the selected time component
    if direction == 'add':
        result_datetime = current_datetime.add(time_component, amount)
    else:
        result_datetime = current_datetime.subtract(time_component, amount)

    return result_datetime